2011-10-09 86 views
4

我有我已经写其[]操作的一类,我想,有时操作者会返回一个INT有时一结构重载类的操作符[]在C++

但编译器不会让我重载操作符,为什么?

它说:“......不能超载”

代码:

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&. 
} 
+2

而你的代码看起来像......? (函数怎样才能有两种不同的返回类型?) –

+0

你能提供一些代码给我们看看你试过了什么吗? – DeCaf

+3

函数可以具有不同的返回类型,只要它的输入类型(或某个模板参数)可以消除歧义。 –

回答

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 { ... }; 

然后调用者将调用object[0]得到一个int结果,或object[as_string(0)]得到string结果。

+0

我想这是因为两个操作员都有相同的论点,谢谢你们。 – Taru

2

函数输出的类型不是函数签名的一部分。因此,您不能同时使用int operator[](int index)Foo operator[](int index)