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

问题描述

假设我有一个Base班:

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的{​​{1}}类:

Base

现在,假设我想为我的class Derived: public Base { public: Derived(float x,float z) : Base(x,y,z,0),r(x),g(y),b(z) {}; float r; float g; float b; }; 类编写一个重载的赋值运算符。目前,这是我的代码

Derived

我需要如上所述分配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; } 类的xyz成员,因为我的{{1 }}类是Base类的重载==运算符,它使用这些成员。例如,考虑以下代码段(假设未在重载的赋值运算符中分配Derived==Base

x

我觉得我做错了这条路;派生类的分配不应该仅与派生类成员有关吗?但是如何使它与基类的重载运算符兼容?有没有更好的方法来实现自己的目标?

解决方法

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

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

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

    return *this;
}