简体   繁体   English

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

[英]Creating Multiple Dynamically Allocated objects in C++

Another question for those far wiser than I: 对于那些比我聪明得多的人,另一个问题是:

I'm trying to create 3 instances of a Player Class like so: 我正在尝试创建一个Player类的3个实例,如下所示:

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

You can see their constructor below. 您可以在下面查看其构造函数。 It's really simple: 这很简单:

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

(just assume name and hitrate are defined properly) (假设名称和命中率定义正确)

Now my problem is this, when I try to check each individual player for their name, it seems they have all become aliases of sorts for player3 现在的问题是,当我尝试检查每个玩家的姓名时,似乎他们都成为了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

Alright, so I'd really like to know the best solution to get around this problem but more importantly I just want to understand why it's behaving this way. 好吧,所以我真的很想知道解决此问题的最佳解决方案,但更重要的是,我只想了解为什么它会采用这种方式。 It seems like such a simple thing (being spoiled by java as I am). 看起来像是一件简单的事情(像我一样被Java宠坏了)。

Also it's important to note: this is for a school assignment and I am told that I MUST use dynamically allocated objects. 同样重要的是要注意:这是用于学校作业的,我被告知必须使用动态分配的对象。

Thanks so much, and do let me know if anything needs clarifying. 非常感谢,如果需要澄清,请告诉我。

Edit: By demand, here are the full files: 编辑:根据需求,这里是完整的文件:

PlayerTest.cpp 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;
}

Player.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

The name and hitrate variables need to be inside the Player class declaration so that each object gets its own separate copies. 名称和命中率变量必须位于Player类声明中,以便每个对象都有自己的单独副本。

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

    private:
        string name;
        double hitrate;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM