繁体   English   中英

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

[英]C++ overloading bracket [] operator get & set with different return types

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

我希望设置器返回对另一个类实例的引用,此举目前还很好,问题是我希望getter返回一个字符,但是在我的主对象中,当我分配字符c = object [5]时]它将调用设置方法而不是获取方法,并返回错误的返回类型。

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

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尝试了所有形式,但没有任何效果。

请给予任何帮助,谢谢!

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

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

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

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

作为一种好的做法,最好将operator[]函数的const版本的返回类型更改为return 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 function. You'll have to change usage of the稍微function. You'll have to change usage of the operator []`函数的function. You'll have to change usage of the

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

暂无
暂无

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

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