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

hal*_*brd 3 c++ constructor class object

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

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

IntelliSense:不存在合适的构造函数可从“Player ()”转换为“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;
};
Run Code Online (Sandbox Code Playgroud)

我对 Player 构造函数的定义:

Player::Player(string name)
{
    SetName(name);
    //Initialize other variables that don't take input
{
Run Code Online (Sandbox Code Playgroud)

以及给出错误的代码:

//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; }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?我尝试过改变

Player1 = Player(Player1Name);
Player2 = Player(Player2Name);
Run Code Online (Sandbox Code Playgroud)

Player1 Player(Player1Name);
Player2 Player(Player2Name);
Run Code Online (Sandbox Code Playgroud)

以及其他一些事情,但没有任何作用。预先非常感谢!

Mat*_*jek 5

Player1Player2是函数。我假设您希望它们成为成员变量。

\n\n

将定义更改Game为:

\n\n
class Game\n{\npublic:\n    Game(bool twoPlayer, string Player1Name, string Player2Name);\n\n    //Get and Set methods (not included)\n\n    //Attributes:\n    Player Player1;\n    Player Player2;\n    int turn;\n};\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
Game::Game(bool twoPlayer, string Player1Name, string Player2Name)\n: Player1(Player1Name)\n, Player2(Player2Name)\n, turn(1)\n{\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

详细了解为什么应该初始化成员:

\n\n\n\n

现在,这两行:

\n\n
Player Game::GetPlayer1() { return Player1; }\nPlayer Game::GetPlayer2() { return Player2; }\n
Run Code Online (Sandbox Code Playgroud)\n\n

不会再产生任何错误。

\n