【问题标题】:Creating Multiple Dynamically Allocated objects in C++在 C++ 中创建多个动态分配的对象
【发布时间】:2012-11-28 23:16:02
【问题描述】:

比我聪明得多的人的另一个问题:

我正在尝试创建 3 个 Player 类的实例,如下所示:

Player *player1 = new Player("Aaron",0.3333333);
Player *player2 = new Player("Bob",0.5);
Player *player3 = new Player("Charlie",1);

你可以在下面看到他们的构造函数。真的很简单:

Player::Player(string n, double hr)
{
    name = n;
    hitrate = hr;
}

(假设名称和命中率定义正确)

现在我的问题是,当我尝试检查每个玩家的名字时,他们似乎都成为了 player3 的别名

//Directly after the player instantiations:
cout << player1->getName() << "\n";
cout << player2->getName() << "\n";
cout << player3->getName() << "\n";

//In the Player.cpp file:
string Player::getName(){
    return name;
}


Outputs: 
Charlie
Charlie
Charlie

好的,所以我真的很想知道解决这个问题的最佳解决方案,但更重要的是,我只想了解它为什么会这样。看起来就是这么简单的事情(像我这样被java宠坏了)。

另外需要注意的是:这是一个学校作业,我被告知我必须使用动态分配的对象。

非常感谢,如果有什么需要澄清的,请告诉我。

编辑:根据需要,以下是完整文件:

PlayerTest.cpp

#include <iostream>
#include <player.h>
using namespace std;

int main(){
    Player *player1 = new Player("Aaron",0.3333333);
    Player *player2 = new Player("Bob",0.5);
    Player *player3 = new Player("Charlie",1);
    cout << player1->getName() << "\n";
    cout << player2->getName() << "\n";
    cout << player3->getName() << "\n";
    return 0;
}

播放器.h

#ifndef PLAYER_H
#define PLAYER_H
#include <string>
using namespace std;

class Player
{
    public:
        Player(string, double);
        string getName();
};

//Player.cpp
#include "Player.h"

string name;
double hitrate;

Player::Player(string n, double hr)
{
    name = n;
    hr = hitrate;
}


string Player::getName(){
    return name;
}

#endif // PLAYER_H

【问题讨论】:

  • "假设 name 和 hitrate 定义正确" NO!
  • 你能发布一个我们可以运行的可编译、独立的程序吗?
  • 是全局声明的名称和命中率还是使用静态?
  • 从你给我们的来看,这大概是你的程序和工作:ideone.com/C2darM
  • 我用我正在使用的 3 个文件的代码编辑了这个问题。我曾想过尝试将其简化为一个文件,但也许我的问题在于它们是如何分离的,而我的任务要求它们是这样的。

标签: c++ instantiation dynamicobject


【解决方案1】:

名称和命中率变量需要在 Player 类声明中,以便每个对象都有自己的单独副本。

class Player
{
    public:
        Player(string, double);
        string getName();

    private:
        string name;
        double hitrate;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2021-09-24
    • 1970-01-01
    相关资源
    最近更新 更多