对象内部对象的重载功能



我有 2 个类 -Boardn数字构建的,并创建一个大小为n*nCell对象的板

class XOBoard {
private:
int n;
Cell **Board;
Cell empty_cell{};
bool valid_range(int y, int x, int n) const;
public: 
Cell& operator[](list<int> list) {
int x = list.front(), y = list.back();
if (!valid_range(y, x, n)) return empty_cell;
return Board[x][y];
}
};

class Cell {
private:
char validate(char in);
public:
char ch;
Cell(char ch = '.');
char getCell() const;
void setCell(char ch);
friend ostream& operator<<(ostream& output, const Cell& cell) {
output << cell.ch;
return output;
}
Cell& operator=(const char another) {
ch = validate(another);
return *this;
}
Cell operator=(const Cell& another) {
Cell empty;     
if (this != &another) {         
if (!(ch != '.' && ch != 'X' && ch != 'O')) {                   
ch = another.ch;                
}
else {
cout << "illegal" << endl;
return empty;
}
}
return *this;
}

};

需求是使这条线工作:char c = board1[{1, 2}].getCell(); cout << c << endl;.

board1[{1, 2}]->这返回一个Cell对象,我希望当有打印或将其放入 char 变量时,它将转到getCell().

我不知道我应该使用哪个运算符重载来执行此操作。

谢谢。

您可以重载索引运算符以采用具有两个 int 成员的结构。

struct Point
{
int x, y;
};

class Board
{
Cell& operator[](Point p)
{
// validate
// return Board[p.x][p.y];
}
}

感谢戴夫给我的解决方案。

要重写该方法char c = board[{1,2}]该板是某个对象,您应该使用:

operator char const() {
return ch;
}

最新更新