一个子类能否使用其父类的赋值运算符重载?

3
我一直在想是否可以创建一个基类,其中包含子类可以使用的运算符重载。
示例(使用模板):
#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: 二进制 'operator':找不到接受右操作数为'type'类型的运算符(或不存在可接受的转换)

编译器:MS Visual C++ 2015

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


2
通常最好包含您得到的精确编译器错误。还要包括编译器名称和版本号。 - Jesper Juhl
1个回答

11

每个类都声明了一个operator=。如果你没有显式地声明,那么这个运算符就会被隐式地声明。这个(可能是隐式的)声明会隐藏基类成员。要取消隐藏,需要使用using声明:

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

虽然这样的过载看起来不是一个非常好的主意。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接