我有一个模板类 Array<T>
定义了以下三个成员函数。
template <typename T>
const T& Array<T>::GetElement(int index) const {
if(index_out_of_bounds(index)) throw OutOfBoundsException(index);
return m_data[index];
}
template <typename T>
T& Array<T>::operator [] (int index) {
if(index_out_of_bounds(index)) throw OutOfBoundsException(index);
return m_data[index];
}
template <typename T>
const T& Array<T>::operator [] (int index) const {
if(index_out_of_bounds(index)) throw OutOfBoundsException(index);
return m_data[index];
}
接下来我有另一个模板类NumericArray<T>
继承自 Array<T>
.此类包含重载运算符 +
.
template <typename T>
NumericArray<T> NumericArray<T>::operator + (const NumericArray<T> &na) const {
unsigned int rhs_size = this -> Size(), lhs_size = na.Size();
if(rhs_size != lhs_size) throw SizeMismatchException(rhs_size, lhs_size);
NumericArray<T> array_sum(rhs_size);
for(unsigned int i = 0; i < rhs_size; i++) {
array_sum[i] = this[i] + na[i];
}
return array_sum;
}
现在假设我实例化了 NumericArray<T>
的两个实例在 main.cpp 中
其中 T 的类型为 int
.两个实例都已填充整数值。
如果我现在尝试执行 +
运算符(operator)我收到以下错误消息:
../NumericArray.tpp:44:16: error: cannot convert ‘NumericArray’ to ‘int’ in assignment array_sum[i] = this[i] + na[i];
但是,如果我返回并更改重载 operator+
的 for 循环中的实现在NumericArray<T>
到以下。运营商如期而至。
array_sum[i] = this -> GetElement[i] + na.GetElement[i];
为什么下标运算符是[]
如果它们具有等效的实现,则表现不一样?
最佳答案
问题是您正在尝试对指针类型应用 operator []
:
for(unsigned int i = 0; i < rhs_size; i++) {
array_sum[i] = this[i] + na[i];
因为 this
是一个指针,你必须要么
1) 首先解引用指针以应用重载运算符。
或
2) 应用 ->
运算符并使用 operator
关键字访问重载运算符。
以下是两种可能解决方案的说明:
array_sum[i] = (*this)[i] + na[i];
或
array_sum[i] = this->operator[](i) + na[i];
对于第二种解决方案,this
不是必需的:
array_sum[i] = operator[](i) + na[i];
关于c++ - 在继承模板类中使用下标[]运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52031138/