假设我有一个 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);
现在,我有一个来自 Base
的 Derived
类:
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
类的 x
、y
和 z
成员,因为我的 Derived
类的 ==
运算符是 Base
类的重载 ==
运算符,它使用这些成员。例如,考虑以下代码段(假设 x
、y
和 z
未在重载赋值运算符中赋值):
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/