【问题标题】:What is the right way to overload the assignment operator for a derived class?为派生类重载赋值运算符的正确方法是什么?
【发布时间】:2020-12-18 05:25:11
【问题描述】:

假设我有一个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 类,它使用这些成员。例如,考虑这个 sn-p(假设 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!

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

【问题讨论】:

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


【解决方案1】:

假设你在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;
}

【讨论】:

  • 虽然我喜欢这个答案的方向,但我认为这是错误的。对base::operator=的调用需要通过a
猜你喜欢
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 2021-07-03
  • 1970-01-01
  • 2014-10-27
相关资源
最近更新 更多