为派生 class 重载赋值运算符的正确方法是什么?

What is the right way to overload the assignment operator for a derived class?

假设我有一个 Base class:

class Base
{   
    public:
        Base(float x, float y, float z, float w): 
                    x(x), y(y), z(z), w(w) {}
        float x;
        float y;
        float z;
        float w;
};
bool operator==(const Base &a, const Base &b);

现在,我有 Derived class 来自 Base:

class Derived: public Base {
    public:
        Derived(float x, float y, float z)
            : Base(x, y, z, 0)
            , r(x), g(y), b(z)
            {};
        float r;
        float g;
        float b;
};

现在,假设我想为 Derived class 编写重载赋值运算符。目前,这是我的代码的样子:

Derived& Derived::operator=(const Derived &a){
    x = a.r;
    y = a.g;
    z = a.b;
    
    r = a.r;
    g = a.g;
    b = a.b;

    return *this;
}

我需要像上面那样分配 Base class 的 xyz 成员,因为 ==我的 Derived class 的运算符是 Base class 的重载 == 运算符,它使用这些成员。例如,考虑这个片段(假设 xyz 未在重载赋值运算符中赋值):

Derived a = Derived(1,2,3);
Derived b = Derived(1,2,3);

bool val = (a == b); // true!

b = Derived(4,5,6);

bool val = (a == b); // still true because b.x, b.y and b.z haven't changed!

我觉得我做错了;派生的 class 的分配不应该只与派生的 class 成员有关吗?但是如何使它与基 class 的重载运算符兼容?有没有更好的方法来实现我正在做的事情?

假设您在 Base class 中有一个 operator=,您可以这样写:

Derived& Derived::operator=(const Derived &a){
    
    Base::operator=(static_cast<Base const&>(a));    

    r = a.r;
    g = a.g;
    b = a.b;

    return *this;
}