【问题标题】:C++ - virtual operator= being called on Base class from Derived instance? [duplicate]C ++ - 虚拟运算符=在派生实例的基类上被调用? [复制]
【发布时间】: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


【解决方案1】:

您忘记的是,无论您编写了什么,您仍然会获得编译器提供的特定于派生的复制赋值运算符。因为它比基类版本更匹配,所以调用默认的。

【讨论】:

  • 嗯,不确定。取决于他认为void Base::operator=(const Base&amp; copyBase) 被调用的原因。
  • @MooingDuck 因为它被隐式生成的Derived &amp; Derived::operator=( const Derived &amp;copy ); 调用,他没有看到
  • 啊,是的,就是这样。这就是我一直在寻找的。很高兴知道:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-01
  • 2018-10-21
  • 1970-01-01
  • 2016-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-04-16
相关资源
最近更新 更多