簡體   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