【问题标题】:Can a child-class use the asignment operator overload of its parent?子类可以使用其父类的赋值运算符重载吗?
【发布时间】:2016-08-09 05:22:53
【问题描述】:

我一直在问自己是否有可能创建一个具有子类可以使用的运算符重载的基类。

示例(带模板):

#include <cassert>

template<typename T>
struct Base {
    T value {};
    Base& operator=(const T& newVal) { this->value = newVal; return *this; }
};

template<typename T>
struct Child : Base<T> {
};

int main() {
    Child<int> ch {};
    assert(ch.value == 0);
    ch = 10;  // compilation error here
    assert(ch.value == 10);
}

我自己尝试过编译错误。如果我想这样做,我应该怎么做?这甚至可能还是我必须使用虚拟并覆盖它(或 有什么可能)?

错误 C2679:二进制“运算符”:找不到运算符 'type' 类型的右手操作数(或者没有可接受的 转换)

编译器:MS Visual C++ 2015

PS:请告诉我解决方案是否使代码变得丑陋。

【问题讨论】:

  • 包含您得到的 exact 编译器错误通常是个好主意。还包括编译器名称和版本。

标签: c++ c++11 assignment-operator


【解决方案1】:

每个类都声明一个operator=。如果您不显式执行此操作,则隐式声明该运算符。该(可能是隐式的)声明隐藏基成员。要取消隐藏,您需要使用using 声明:

template <typename T>
struct Child : Base<T>
{
    using Base<T>::operator=;
};

【讨论】:

  • 虽然这样的过载似乎不是一个非常好的主意。
猜你喜欢
  • 2019-04-16
  • 2021-05-08
  • 2021-10-22
  • 2016-01-04
  • 2017-10-07
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
相关资源
最近更新 更多