简体   繁体   中英

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

I'm trying to overload the [] operator for a class that I created with different return types for the getter and setter.

I want the setter to return a reference to a another class instance, which is happening fine at the moment, the problem is that I want the getter to return a char, but in my main when i'm assigning char c = object[5] it's calling the setter instead of the getter and returning the wrong return type.

That how it looks in my code:

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;

That line results in error: no suitable conversion function from "Board_Node" to "char" exists.

Already tried all forms with const everywhere and nothing worked.

Appericiate any help, thank you!

Calling the overloaded functions getters and setters based on whether an object is const or non- const is not appropriate.

The non- const version of the overload is given higher priority if the object is not const .

I suggest adding an explicitly named getter function, which can use the overloaded operator[] function.

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

As a matter of good practice, it will be better to change the return type of the const version of the operator[] function to return Board_Node const& .

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

That will allow you to extract other information from the corresponding Board_Node , not just a char .

With that, you won't need the 'get function. You'll have to change usage of the function. You'll have to change usage of the operator[]` function a bit.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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