c++ - 在 C++ 中重载类的运算符 []

标签 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&.
}

最佳答案

您不能根据返回类型重载函数。您可以让您的运算符(operator)返回一个 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 { ... };

然后调用者将调用 object[0] 来获取 int 结果,或者调用 object[as_string(0)] 来获取string 结果。

关于c++ - 在 C++ 中重载类的运算符 [],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7705492/

相关文章:

c++ - 如何将指向具有任意参数的函数的指针作为模板参数?

c++ - Concurrency::critical_section 构建错误:无法访问私有(private)成员

java - Java中调用了哪个重载方法

php 重载等于运算符

c++ - 近似排序(数组/vector ),可预测的运行时间

c - 如何在 if 语句中的条件下创建宏

c++ - 在使用 std::set 时重载运算符 <

Go:(运算符 + 未在 slice 上定义)

c++ - 为什么下标运算符 C++ 经常成对出现?

c++ - 如何通过Matlab Mex编译工具使用C++编译器