2010-10-07 56 views
0

超载[]的问题,这是我的泛型类:在2个变化

template<class T, class PrnT> 
class PersonalVec { 

public: 
    PersonalVec(); 
    T &operator[](int index) const; 
    const T &operator[](int index) const; 

private: 
    std::vector<T> _vec; 

}; 

我需要实施2个版本的[]操作:
一个会返回一个const引用和经常一个这也将返回一个参考。 当我编译它,我得到:
PersonalVec.hpp:23: error: ‘const T& PersonalVec<T, PrnT>::operator[](int) const’ cannot be overloaded
PersonalVec.hpp:22: error: with ‘T& PersonalVec<T, PrnT>::operator[](int) const

我已经把其中一方的言论,然后它编译,所以我想他们已经在某种程度上发生碰撞。什么是问题,我该如何解决它?

谢谢!

回答

-1

函数的返回类型不是可用于重载函数的条件。 函数可以被重载,如果:
1的不同参数没有
2的参数不同的充序列或
3.不同类型的参数

您正在尝试基于返回类型,因此过载功能它给出了错误。
'const'关键字可以帮助您重载函数,即使上述3个标准不符合。所以简单的解决方案可以是使其中的一个函数为const并将其他函数作为正常函数来使用

3

您需要:

T &operator[](int index); 
const T &operator[](int index) const; 

即非const运算符返回非const引用和const一个返回常量引用。

2

您不能基于返回类型进行重载,您只能根据参数类型进行重载,包括成员函数的隐藏this参数。

该类型的函数调用表达式,或涉及潜在的过载操作者的表达,是通过重载解析所选择的功能类型来确定,就不能迫使这样的表达具有特定的类型,并尝试影响重载解析从返回类型。

您需要根据参数类型或thisconst的内容给出您的重载函数签名,或者您需要选择一种适当的返回类型并具有单个函数。

0

返回非const引用时,需要删除函数的常量。

T &operator[](int index);
const T &operator[](int index) const;

超载不和不能返回类型发生。