对象内部对象的重载功能

时间:2019-12-13 10:07:34

标签: c++ arrays object operator-overloading

我有2个类-为Board编号构建的n,并创建了一个大小为Cell的{​​{1}}对象的面板

n*n

};

需求是使此行有效: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}]对象,我希望当有打印内容或将其放入char变量时,它将转到Cell

我不知道该使用哪个运算符重载。

谢谢。

2 个答案:

答案 0 :(得分:0)

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

struct Point
{
    int x, y;
};


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

答案 1 :(得分:0)

感谢戴夫给我解决方案。

要覆盖char c = board[{1,2}]方法是木板是某种对象,应使用:

operator char const() {
    return ch;
}
相关问题