使用自定义构造函数将对象实例化为类属性(C ++)

时间:2015-04-20 09:52:49

标签: c++ class object constructor

我正在使用C ++编写标准的Battleship游戏,其中Game对象包含两个Player对象。当我尝试在Game构造函数中实例化Player对象时,IntelliSense给了我两个错误:

  

IntelliSense:表达式必须是可修改的左值

     

IntelliSense:没有合适的构造函数可以转换为" Player()"到"播放器"

这是我的头文件:

class Player {
public:
    Player(string name);
    //More unrelated stuff (Get/Set methods and Attributes)
};


class Game {
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);
    //Get and Set methods (not included)
    //Attributes:
    Player Player1();
    Player Player2();
    int turn;
};

我对Player构造函数的定义:

Player::Player(string name)
{
    SetName(name);
    //Initialize other variables that don't take input
{

以及给出错误的代码:

//Game constructor
Game::Game(bool twoPlayer, string Player1Name, string Player2Name)
{
    Player1 = Player(Player1Name);  //These two lines give the first error
    Player2 = Player(Player2Name);
    turn = 1;
}

//Game class Gets
int Game::GetTurn() { return turn; }
Player Game::GetPlayer1() { return Player1; }  //These two lines give the second error
Player Game::GetPlayer2() { return Player2; }

我做错了什么?我试过改变

Player1 = Player(Player1Name);
Player2 = Player(Player2Name);

Player1 Player(Player1Name);
Player2 Player(Player2Name);

和其他一些事情,但没有任何作用。非常感谢提前!

2 个答案:

答案 0 :(得分:2)

问题似乎出现在头文件中的Game类中:

class Game {
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);
    //Get and Set methods (not included)
    //Attributes:
    Player Player1;// 
    Player Player2;//  
    int turn;
}; 

在声明你的成员时删除括号,否则你正在创建不带参数的名为Player1和Player2的函数

答案 1 :(得分:1)

Player1Player2是函数。我假设你希望它们是一个成员变量。

Game定义更改为:

class Game
{
public:
    Game(bool twoPlayer, string Player1Name, string Player2Name);

    //Get and Set methods (not included)

    //Attributes:
    Player Player1;
    Player Player2;
    int turn;
};

使用初始化列表初始化您的成员:

Game::Game(bool twoPlayer, string Player1Name, string Player2Name)
: Player1(Player1Name)
, Player2(Player2Name)
, turn(1)
{
}

详细了解您应该初始化成员的原因:

现在,这两行:

Player Game::GetPlayer1() { return Player1; }
Player Game::GetPlayer2() { return Player2; }

不会再产生任何错误。