在模板数组的 class 中使用下标运算符
Using subscript operator within a class on a template array
..
..
..
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 访问它时它才起作用。
我如何访问 class 中的运算符?
我在这里搜索并找到了一个对我不起作用的灵魂 (*this)。
您使用 (*this)
找到的解决方案是正确的,但您的 operator[]
return 类型错误,因此没有正确的使用方法。将 return 从 T
更改为 T&
:
T& operator[](int i){
if( i > sizes || i<0 ){
cout << "Index out of bounds" << endl;
return arr[0];
}
return arr[i];
}
然后您可以在 class 中使用它:
(*this)[curSize] = element;
你也应该有一个 const 版本:
T const& operator[](int i) const {
if( i > sizes || i<0 ){
cout << "Index out of bounds" << endl;
return arr[0];
}
return arr[i];
}
另一种编写 const 和非 const 版本(以避免重复代码)的方法是使用 const_cast
将一个人委托给另一个人。
还要注意检查i<0
的必要性。这就是 i
和 sizes
都成为 unsigned
以避免额外检查会更好的原因。优化器应该修复额外检查的明显低效,即使您保留类型已签名。但是额外的检查仍然使源代码混乱并且忘记它(就像您所做的那样)仍然是一个容易犯的错误。因此,对永远不会正确为负的值使用 int
是不好的做法。
..
..
..
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 访问它时它才起作用。 我如何访问 class 中的运算符? 我在这里搜索并找到了一个对我不起作用的灵魂 (*this)。
您使用 (*this)
找到的解决方案是正确的,但您的 operator[]
return 类型错误,因此没有正确的使用方法。将 return 从 T
更改为 T&
:
T& operator[](int i){
if( i > sizes || i<0 ){
cout << "Index out of bounds" << endl;
return arr[0];
}
return arr[i];
}
然后您可以在 class 中使用它:
(*this)[curSize] = element;
你也应该有一个 const 版本:
T const& operator[](int i) const {
if( i > sizes || i<0 ){
cout << "Index out of bounds" << endl;
return arr[0];
}
return arr[i];
}
另一种编写 const 和非 const 版本(以避免重复代码)的方法是使用 const_cast
将一个人委托给另一个人。
还要注意检查i<0
的必要性。这就是 i
和 sizes
都成为 unsigned
以避免额外检查会更好的原因。优化器应该修复额外检查的明显低效,即使您保留类型已签名。但是额外的检查仍然使源代码混乱并且忘记它(就像您所做的那样)仍然是一个容易犯的错误。因此,对永远不会正确为负的值使用 int
是不好的做法。