Domanda

Another question for those far wiser than I:

I'm trying to create 3 instances of a Player Class like so:

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

//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).

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

#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
È stato utile?

Soluzione

The name and hitrate variables need to be inside the Player class declaration so that each object gets its own separate copies.

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

    private:
        string name;
        double hitrate;
};
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top