C ++重载括号[]运算符get&设置不同的返回类型

时间:2018-05-08 18:12:28

标签: c++ visual-studio class operator-overloading operators

我正在尝试为我使用getter和setter的不同返回类型创建的类重载[]运算符。

我希望setter返回对另一个类实例的引用,此时此刻发生正常,问题是我希望getter返回一个char,但是在我的main中我指的是char c = object [5]它调用setter而不是getter并返回错误的返回类型。

它在我的代码中看起来如何:

Board.h

const char& operator[](Board_Node index) const;
Board_Node& operator[](Board_Node index);

Board.cpp

const char& Board::operator[](Board_Node index) const
{
    int boardIndex = index.i * _boardSize + index.j;
    if (boardIndex < 0 || boardIndex >= _board.size())
    {
        throw IllegalCoordinateException(index.i, index.j);
    }
    return _board[index.i * _boardSize + index.j].token;
}

Board_Node & Board::operator[](Board_Node index)
{
    int boardIndex = index.i * _boardSize + index.j;
    if (boardIndex < 0 || boardIndex >= _board.size())
    {
        throw IllegalCoordinateException(index.i, index.j);
    }
    return _board[index.i * _boardSize + index.j];
}

的main.cpp

char c = board1[{1, 2}]; cout << c << endl;

该行导致错误:不存在从“Board_Node”到“char”的合适转换函数。

已经尝试过使用const的所有表单,并且没有任何效果。

请求任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

根据对象是const还是非 - const来调用重载函数getter和setter是不合适的。

如果对象不是const,则非const版本的重载优先级更高。

我建议添加一个明确命名的getter函数,该函数可以使用重载的operator[]函数。

char get(Board_Node index) const
{
   return (*this)[index];
}

作为一种良好做法,最好更改const函数的operator[]版本的返回类型以返回Board_Node const&

Board_Node const& operator[](Board_Node index) const;
Board_Node& operator[](Board_Node index);

这样您就可以从相应的Board_Node中提取其他信息,而不仅仅是char

有了这个,你不再需要{get function. You'll have to change usage of the operator []`函数。

char c = board1[{1, 2}].token;
cout << c << endl;
相关问题