【问题标题】:Using the subscript [] operator in inherited template class在继承的模板类中使用下标 [] 运算符
【发布时间】: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&lt;T&gt;,它继承自Array&lt;T&gt;。此类包含重载运算符+

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&lt;T&gt; 实例 其中 T 的类型为 int。两个实例都已填充整数值。

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

../NumericArray.tpp:44:16: 错误:无法在赋值中将“NumericArray”转换为“int” array_sum[i] = this[i] + na[i];

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

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

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

【问题讨论】:

  • this 是一个指针,而不是一个对象。运算符重载适用于对象,这意味着您必须取消引用指针才能获取对象,不是吗?
  • 我只是把脸用力了。
  • 另外,如果你有一个复制构造函数,最好重载+=,然后按照+=调用operator +。然后代码变成+ 的单行代码。 return NumericArray&lt;T&gt;(*this) += na;
  • 顺便说一句,考虑将非const 成员的正文重写为return const_cast&lt;T&gt;((*this)[i]);。减少重复是好的。此外,它们可能都应该在课堂上定义。
  • 从好的方面来说,如果*this 是数组的成员,this[i] 并不总是无稽之谈。 ;)

标签: c++ templates inheritance operator-overloading


【解决方案1】:

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

 for(unsigned int i = 0; i < rhs_size; i++) {
        array_sum[i] = this[i] + na[i];

由于this 是一个指针,你必须要么

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

2) 应用-&gt; 运算符并使用operator 关键字访问重载的运算符。

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

    array_sum[i] = (*this)[i] + na[i];

    array_sum[i] = this->operator[](i) + na[i];

使用第二种解决方案,this 不是必需的:

    array_sum[i] = operator[](i) + na[i];

【讨论】:

  • 我相信第二种解决方案可以删除this-&gt;
猜你喜欢
  • 1970-01-01
  • 2020-03-27
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 2020-10-14
  • 1970-01-01
相关资源
最近更新 更多