【问题标题】:Instantiating object as a class attribute with custom constructor (C++)使用自定义构造函数将对象实例化为类属性 (C++)
【发布时间】:2015-04-20 09:52:48
【问题描述】:

我正在使用 C++ 编写一个标准的 Battleship 游戏,其中包含一个 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;
};

我对 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);

还有很多其他的东西,但没有任何效果。提前非常感谢!

【问题讨论】:

  • Player Player1(); 是一个函数声明。

标签: c++ class object constructor


【解决方案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; }

不会再产生任何错误。

【讨论】:

    【解决方案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 且不带参数的函数

    【讨论】:

    • 啊!就是这样!非常感谢!
    猜你喜欢
    • 2012-11-05
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多