如何解决对派生类重载赋值运算符的正确方法是什么?
假设我有一个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;
}
类的x
,y
和z
成员,因为我的{{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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。