child-class 可以使用其 parent 的赋值运算符重载吗?

Can a child-class use the asignment operator overload of its parent?

我一直在问自己是否有可能创建一个基础 class,其中 operator-overloads 可供 child-class(es) 使用。

示例(带模板):

#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);
}

我自己用 Compile-Error 试了一下。如果我想那样做怎么办?这甚至可能还是我必须使用虚拟并覆盖它(或 一切皆有可能)?

Error C2679: binary 'operator' : no operator found which takes a right-hand operand of type 'type' (or there is no acceptable conversion)

Compiler: MS Visual C++ 2015

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

每个 class 声明一个 operator=。如果您不明确地执行此操作,则运算符将被隐式声明。该(可能是隐含的)声明 隐藏了 基本成员。要取消隐藏它,您需要使用 using 声明:

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