在继承的模板类中使用下标[]运算符

Mut*_*thm 0 c++ inheritance templates operator-overloading

我有一个模板类Array<T>,定义了以下三个成员函数。

\n\n
template <typename T>\nconst T& Array<T>::GetElement(int index) const {\n    if(index_out_of_bounds(index)) throw OutOfBoundsException(index);\n    return m_data[index];\n}\n\ntemplate <typename T>\nT& Array<T>::operator [] (int index) {\n    if(index_out_of_bounds(index)) throw OutOfBoundsException(index);\n    return m_data[index];\n}\n\ntemplate <typename T>\nconst T& Array<T>::operator [] (int index) const {\n    if(index_out_of_bounds(index)) throw OutOfBoundsException(index);\n    return m_data[index];\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

接下来我有另一个NumericArray<T>继承自 的模板类Array<T>。此类包含一个重载运算符+

\n\n
template <typename T>\nNumericArray<T> NumericArray<T>::operator + (const NumericArray<T> &na) const {\n    unsigned int rhs_size = this -> Size(), lhs_size = na.Size();\n    if(rhs_size != lhs_size) throw SizeMismatchException(rhs_size, lhs_size);\n\n    NumericArray<T> array_sum(rhs_size);\n\n    for(unsigned int i = 0; i < rhs_size; i++) {\n        array_sum[i] = this[i] + na[i];\n    }\n\n    return array_sum;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

现在假设我在 main.cpp\n 中实例化两个实例,其中NumericArray<T>T 的类型为int。两个实例都已填充了整数值。

\n\n

如果我现在尝试执行该+运算符,我会收到以下错误消息:

\n\n
\n

../NumericArray.tpp:44:16: 错误: 无法在赋值中将 \xe2\x80\x98NumericArray\xe2\x80\x99 转换为 \xe2\x80\x98int\xe2\x80\x99\n array_sum[i] = this [i] + na[i];

\n
\n\n

但是,如果我返回并将重载的 for 循环中的实现更改operator+NumericArray<T>以下内容。操作员按照预期执行操作。

\n\n

array_sum[i] = this -> GetElement[i] + na.GetElement[i];

\n\n

如果下标运算符[]具有等效的实现,为什么它们的行为不一样?

\n

Pau*_*zie 5

问题是您正在尝试应用于operator []指针类型:

 for(unsigned int i = 0; i < rhs_size; i++) {
        array_sum[i] = this[i] + na[i];
Run Code Online (Sandbox Code Playgroud)

由于this是一个指针,您必须

1)首先取消引用指针以应用重载运算符。

或者

2)应用->运算符并使用operator关键字访问重载运算符。

以下是两种可能的解决方案的说明:

    array_sum[i] = (*this)[i] + na[i];
Run Code Online (Sandbox Code Playgroud)

或者

    array_sum[i] = this->operator[](i) + na[i];
Run Code Online (Sandbox Code Playgroud)

使用第二种解决方案,则this不需要:

    array_sum[i] = operator[](i) + na[i];
Run Code Online (Sandbox Code Playgroud)