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

标签 c++ oop inheritance operator-overloading c++17

假设我有一个 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);

现在,我有一个来自 BaseDerived 类:

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 类编写一个重载的赋值运算符。目前,我的代码如下所示:

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 类的 xyz 成员,因为我的 Derived 类的 == 运算符是 Base 类的重载 == 运算符,它使用这些成员。例如,考虑以下代码段(假设 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!

我觉得我这样做的方式是错误的;派生类的赋值不应该只涉及派生类成员吗?但如何使其与基类的重载运算符兼容呢?有更好的方法来实现我正在做的事情吗?

最佳答案

假设您在 Base 类中有一个 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;
}

关于c++ - 重载派生类的赋值运算符的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63647981/

相关文章:

c++ - 虚方法在多重继承下表现不同

背包分支定界的C++实现

c++ - 在 C++ 中包含头文件时的循环类依赖

c++ - 为什么我可以静态调用实例函数?

c++ - 允许在派生类上使用流运算符

entity-framework - 对继承的实体使用 Include()

c++ - 如何在 C++ 中最大化 SSD I/O?

c++ - 从基类继承构造函数?

c# - 清洁代码 : SRP and Open/Closed when fetching data from web services

java - 如何在数据库中保存层次结构类?