简体   繁体   中英

Overloading class' operator [] in C++

I have a class which I have written its [] operator, and I want that sometimes the operator will return an int and sometimes a struct .

But the compiler won't let me overload the operator, why?

It says:"...cannot be overloaded"

Code:

template <class T> struct part
{ };


template <class T> class LinkedList
{
         public:
                LinkedList() : size(0), head(0) {}
                T& operator[](const int &loc);
                part<T>& operator[](const int &loc);
};

template <class T> T& LinkedList<T>::operator[](const int &loc)
{
         ..a lot of thing which compiles perfectly
}

template <class T> part<T>& LinkedList<T>::operator[](const int &loc)
{
         ...the same thing but returns struct&.
}

You can't overload a function based on the return type. You could have your operator return a variant of int and string, and let the user check which was actually returned, but its cumbersome. If the return type can be determined at compilation time, you can implement the operator overloads by mean of having different indices types. Something like this:

struct as_string
{
    as_string( std::size_t index ) : _index( index ){}

    std::size_t const _index;
};

...

int operator[]( int index ) const { ... };
std::string operator[]( as_string const& index ) const { ... };

And then the caller would invoke object[0] to get an int result, or object[as_string(0)] to get a string result.

The type of a function's output is not a part of the function's signature. Thus you can't use both int operator[](int index) and Foo operator[](int index) .

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