简体   繁体   English

对象内对象的重载函数

[英]Overloading function for object inside object

I've 2 Classes - Board built for n number and create a board of Cell object of size n*n我有2类- Board专为n数量和创造的董事会Cell大小的物体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;
    }

}; };

The demand is to make this line work: char c = board1[{1, 2}].getCell(); cout << c << endl;需求是让这条线工作: char c = board1[{1, 2}].getCell(); cout << c << endl; char c = board1[{1, 2}].getCell(); cout << c << endl; . .

board1[{1, 2}] -> this return an Cell object, and I want when there is a print or put it into char variable it will go to getCell() . board1[{1, 2}] -> 这将返回一个Cell对象,我希望当有打印或将其放入 char 变量时,它将转到getCell()

I do not know which operator overloading i should use to do it.我不知道我应该使用哪个运算符重载来做到这一点。

Thanks you.谢谢。

You can overload the index operator to take a structure which has two int members.您可以重载索引运算符以采用具有两个 int 成员的结构。

struct Point
{
    int x, y;
};


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

Thanks for dave for giveing me the solution.感谢戴夫给我解决方案。

To override the method char c = board[{1,2}] that board is some object, you should use:要覆盖方法char c = board[{1,2}]该 board 是某个对象,您应该使用:

operator char const() {
    return ch;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM