[英]Creating Multiple Dynamically Allocated objects in C++
對於那些比我聰明得多的人,另一個問題是:
我正在嘗試創建一個Player類的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;
}
(假設名稱和命中率定義正確)
現在的問題是,當我嘗試檢查每個玩家的姓名時,似乎他們都成為了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寵壞了)。
同樣重要的是要注意:這是用於學校作業的,我被告知必須使用動態分配的對象。
非常感謝,如果需要澄清,請告訴我。
編輯:根據需求,這里是完整的文件:
#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;
}
#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;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.