【发布时间】:2015-04-18 14:55:14
【问题描述】:
我在覆盖 operator= 重载时遇到问题。当我尝试使用运算符将一个 Derived 对象复制到另一个时,它完全避免了 Derived 覆盖,而只是调用 Base operator= :
class Base
{
public:
virtual Base* clone() const;
protected:
virtual void operator=(const Base& copyBase);
}
class Derived : public Base
{
public:
Derived* clone() const;
private:
void operator=(const Base& copyBase) override;
}
Derived* Derived::clone() const
{
Derived* clone = new (std::nothrow) Derived();
if(clone)
{
*clone = *this; // <--- Base operator= get's called
}
return clone;
}
Derived::clone() 被正确调用,但不是调用 Derived::operator=,而是跳转到 Base::operator=,我似乎不知道为什么。 virtual operator= 有什么特别之处还是我在做一些傻事?
【问题讨论】:
-
赋值运算符是不继承的。
-
为什么不
Derived* clone = new (std::nothrow) Derived(*this);它更短更高效。 -
很少有
operator=()需要虚拟的情况。operator=应始终使用 self 类型的参数定义。 (另外,不要让它返回void) -
@PaulMcKenzie 赋值运算符被继承,但总是被隐式声明的赋值运算符隐藏。
-
@Brian 是的,感谢您澄清这一点。派生类的用户定义的赋值运算符不会自动调用来自基类的赋值运算符。派生类版本必须显式调用基类赋值运算符。
标签: c++ polymorphism operator-overloading virtual