在C++中创建多个动态分配的对象
Creating Multiple Dynamically Allocated objects in C++
对于那些比我聪明得多的人来说,另一个问题:
我正在尝试创建 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;
};
相关文章:
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 动态分配对象中的字段-动态分配更好还是静态分配更好?C++
- 如何使用每个对象的单个构造函数参数动态分配C++对象数组?
- 将动态分配对象传递到 boost::any 构造函数中
- C 删除指向动态分配对象的指针
- 有关动态分配对象的问题
- 如何删除用于动态分配对象的智能指针
- C++函数返回指向动态分配对象的指针
- 如何创建指向动态分配对象的指针向量
- 动态分配对象数组,如 int
- 复制构造动态分配对象的问题
- 在类中动态分配对象指针的2D数组
- 在C++循环中正确删除动态分配对象的位置
- 如何获取指向动态分配对象的指针的基址
- 动态分配对象数组
- 如何删除指向动态分配对象的指针数组
- 返回对动态分配对象的引用
- 动态分配对象生成器
- 如何正确管理动态分配对象的内存
- 为什么valgrind显示泄漏,即使包含动态分配对象的向量被释放