Program class inproper use!?

fPlayers[0].Player(tmp1Name, 'X');

this line is erroring... i have all the appropriate header files included. fPlayers is an array of Player instances that is declared in the driver.h but the above line is in the driver.cpp...

So player.h and player.cpp

then driver.h (which has an array of players [fPlayers] declared as private in i) and driver.cpp

Invalid use of class 'Player'

any ideas would be helpful! Thanks heaps!
Can you post your Player class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Player::Player() {}

Player::Player( string aName, char aSymbol )
{
    fPlayerName = aName;
    fPlayerSymbol = aSymbol;
}

char Player::getSymbol() const
{
    return fPlayerSymbol;
}

const string& Player::getName() const
{
    return fPlayerName;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Player
{
private:
	char fPlayerSymbol;
	string fPlayerName;

public:
	static Player NIL;

	Player();
    Player(string aName, char aSymbol );
    char getSymbol() const;
    const string& getName() const;
};


Here is the header file if it helps
I see, you're trying to construct the array of players.

The constructor gets called when the object is created. So that means you need to construct it at that point. There are number of ways to do this, but the most somple might be to declare an array of pointer, then create the objects wher you have that code.

1
2
const size_t nPlayers = 20;
Players* fPlayers[nPlayers];


Then later on:
 
fPlayer[0] = new Player(tmp1Name, "X");


You can use it like this:
 
std::string name = fPlayer[0]->getName();
Last edited on
Anyway to do it without an array of pointer?
closed account (D80DSL3A)
Add an INIT function to the class for setting the member values.
1
2
3
4
5
void Player::INIT( string aName, char aSymbol )
{
    fPlayerName = aName;
    fPlayerSymbol = aSymbol;
}

You can call it after the array is default constructed.
fPlayers[0].INIT(tmp1Name, 'X');
Another option:

1
2
3
4
5
Player fPlayers[5] = {
    Player(tmp1Name, 'X'),
    Player(tmp2Name, 'Y'),
    // ... etc
    };


But note this must be done when the array is created, since that is when the objects are all constructed.
Topic archived. No new replies allowed.