C++ 为派生类重载赋值运算符的正确方法是什么?
假设我有一个C++ 为派生类重载赋值运算符的正确方法是什么?,c++,oop,inheritance,operator-overloading,c++17,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
类:
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
派生的类:
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::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
成员,因为我的派生的类的=
操作符是使用这些成员的Base
类的重载=
操作符。考虑这个片段,例如(假设代码> x,<代码> y和<代码> z < /COD>未在重载赋值运算符中分配):
我觉得我这样做是错误的;派生类的赋值不应该只涉及派生类成员吗?但如何使它与基类的重载运算符兼容?有没有更好的方法来实现我正在做的事情?假设您在基本类中有一个操作符=
,您可以编写:
Derived& Derived::operator=(const Derived &a){
Base::operator=(static_cast<Base const&>(a));
r = a.r;
g = a.g;
b = a.b;
return *this;
}
Derived&Derived::operator=(const-Derived&a){
Base::operator=(static_cast(a));
r=a.r;
g=a.g;
b=a.b;
归还*这个;
}
闻起来你的层次结构违反了。但我假设这只是一个人为的例子来支持你的问题。虽然我喜欢这个答案的方向,但我认为它是错误的。对base::operator=
的调用需要传递a
Derived& Derived::operator=(const Derived &a){
Base::operator=(static_cast<Base const&>(a));
r = a.r;
g = a.g;
b = a.b;
return *this;
}