【发布时间】:2018-08-27 00:04:07
【问题描述】:
我有一个模板类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;
}
现在假设我在 main.cpp 中实例化了两个 NumericArray<T> 实例
其中 T 的类型为 int。两个实例都已填充整数值。
如果我现在尝试执行 + 运算符,我会收到以下错误消息:
../NumericArray.tpp:44:16: 错误:无法在赋值中将“NumericArray”转换为“int” array_sum[i] = this[i] + na[i];
但是,如果我返回并将 NumericArray<T> 中重载的 operator+ 的 for 循环中的实现更改为以下内容。操作员按预期执行。
array_sum[i] = this -> GetElement[i] + na.GetElement[i];
如果下标运算符 [] 具有相同的实现,为什么它们的行为不一样?
【问题讨论】:
-
this是一个指针,而不是一个对象。运算符重载适用于对象,这意味着您必须取消引用指针才能获取对象,不是吗? -
我只是把脸用力了。
-
另外,如果你有一个复制构造函数,最好重载
+=,然后按照+=调用operator +。然后代码变成+的单行代码。return NumericArray<T>(*this) += na; -
顺便说一句,考虑将非
const成员的正文重写为return const_cast<T>((*this)[i]);。减少重复是好的。此外,它们可能都应该在课堂上定义。 -
从好的方面来说,如果
*this是数组的成员,this[i]并不总是无稽之谈。 ;)
标签: c++ templates inheritance operator-overloading