当类是子类时重载赋值运算符
如何使用赋值运算符实现设置基类成员?例如,如果有人在派生类中定义赋值运算符,如下所示:(
其中 colour
和 Colour()
都是基类的成员 - 意味着下面指示的行是非法)
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
{
Colour(rhs.colour); // not allowed
Colour(rhs.Colour()); // not allowed
}
return *this;
}
解决办法是什么?有没有办法在基础中链接运算符重载?我是否要做类似的事情...
Derived& Derived::operator=(const Derived& rhs) : Base::operator=(rhs)
...?
How do you set base class members using the assignment operator implementation? If for example someone defines the assignment operator in a derived class like this:
(where both colour
and Colour()
are members of the base class - meaning the lines indicated below are illegal)
Derived& Derived::operator=(const Derived& rhs)
{
if (&rhs != this)
{
Colour(rhs.colour); // not allowed
Colour(rhs.Colour()); // not allowed
}
return *this;
}
what is the solution? Is there a way of linking operator overloads in the base? Do I do something like...
Derived& Derived::operator=(const Derived& rhs) : Base::operator=(rhs)
...?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
它是这样完成的:
It is done like this :
你已经很接近了,只需将该调用放入方法主体中即可。
You're close, just put that call in the method body.
您应该能够使用公共访问器和修改器:
否则,请在基类中保护成员,以便派生类可以访问:
第三种选择可能是在基类中定义公共赋值运算符,并让派生类调用基类操作员:
这是一个完整的测试用例:
You should be able to use public accessors and mutators:
Otherwise make the members protected in the base class so that derived classes have access:
A third option could be to define an assignment operator public in the base class and have your derived class call the base operator:
Here's a complete test case:
如果您想从派生类调用基类运算符=,我会在基类运算符中实现分配/构造颜色的operator=功能:
在派生类operator=()实现中。据我所知,您为 Derived operator= 提议的签名不是有效的 C++。
I implement the operator= functionality assigning/constructing color in the Base class operator if you want to call the Base operator= from the Derived class use:
in the Derived class operator=() implementation. The signature you've proposed for Derived operator= isn't valid C++ as far as I know.