在C++中创建多个动态分配的对象

Creating Multiple Dynamically Allocated objects in C++

本文关键字:动态分配 对象 C++ 创建      更新时间:2023-10-16

对于那些比我聪明得多的人来说,另一个问题:

我正在尝试创建 3 个播放器类实例,如下所示:

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;
}

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

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

//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宠坏了)。

同样重要的是要注意:这是针对学校作业的,我被告知我必须使用动态分配的对象。

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

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

玩家测试.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

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

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