与另一个类 c++ 共享对象

Sharing the object with an another class c++

本文关键字:共享 对象 c++ 另一个      更新时间:2023-10-16

>我有两个类:棋盘类和玩家类。棋盘需要在玩家之间共享。我在播放器 cpp 文件中收到错误,说"'玩家::板':必须在构造函数库/成员初始值设定项列表中初始化"

这是我的播放器头文件:

class Player {
private:
    Board &board;
    string name;  // I put a reference
};

播放器 CPP 文件中

// I pass the board in the board class by refrence but get the above error
Player::Player(string n,Board&b) {   
    name=n;
    board=b;
}

同时,我的董事会类看起来像这样:

class Board {
private:
    int** board;
    int row;
    int column;
};
Board::Board(int r,int c)  {
    row=r;
    column=c;
    board=new value*[r];
    for(int i=0;i<r;i++) {
        board[i] = new value[c];
    }
}

不能延迟初始化引用。正如错误告诉您的那样,您需要在成员 init 列表中初始化它,例如:

Player::Player(string n,Board&b) : board(b) // preferably also ,name(n)
{
    // rest of implementation
}

最好还应该初始化成员 init 列表中的name,并通过const引用传递string n,例如 const string& n ,这样就可以避免额外的副本。如果使用 g++ ,则可以使用 -Weffc++ 编译器标志,该标志将为您提供有关成员列表初始化等的警告。

尽量避免将引用用作类数据成员。一些常见问题:

  • 您必须在每个构造函数初始列表中初始化引用,
  • 语义可能会令人困惑,
  • 引用非常适合将参数传递给方法,
  • 引用不允许分配

相反,尝试使用指针作为数据成员,这样可以避免问题,并且代码将更具可读性。

编辑:如果您需要在所有玩家之间共享单个板对象,那么您可以使用单例。