在C++中重载类'operator []

Tar*_*aru 4 c++ overloading operator-keyword

我有一个类,我编写了它的[]运算符,我希望有时运算符将返回一个int,有时返回一个struct.

但是编译器不会让我重载运算符,为什么呢?

它说:"......不能超载"

码:

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&.
}
Run Code Online (Sandbox Code Playgroud)

K-b*_*llo 6

您不能基于返回类型重载函数.您可以让您的运算符返回int和string的变体,并让用户检查实际返回的内容,但是它很麻烦.如果可以在编译时确定返回类型,则可以通过具有不同的索引类型来实现运算符重载.像这样的东西:

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 { ... };
Run Code Online (Sandbox Code Playgroud)

然后调用者将调用object[0]以获得int结果,或者object[as_string(0)]获得string结果.