【发布时间】:2015-12-23 12:59:25
【问题描述】:
..
..
..
const int sizes = 50;
template<class T>
class List {
private:
int curSize;
T arr[sizes];
public:
List<T>(){
cout << "constructor called\n";
this->curSize = 0;
}
void add(T element) {
arr[curSize] = element;
this->curSize++;
}
..
..
..
T operator[](int i){
if( i > sizes ){
cout << "Index out of bounds" << endl;
return arr[0];
}
return arr[i];
}
当我调用 add 函数时,运算符重载对我不起作用,只有当我尝试从 main.cpp 访问它时它才起作用。 我怎样才能访问类内的运算符? 我在这里搜索,发现一个对我不起作用的灵魂乐(*this)。
【问题讨论】:
-
您是否希望
arr[curSize]致电T operator[](int i)? -
add函数在arr上使用[]运算符,它不是您的类的实例,因此不会调用重载运算符。
标签: c++ operator-overloading operator-keyword