C ++ - 虚拟运算符=从派生实例的基类调用?

时间:2015-02-17 19:25:50

标签: c++ polymorphism operator-overloading virtual

我遇到了覆盖operator = overload的问题。当我尝试使用运算符将​​一个Derived对象复制到另一个时,它完全避免了Derived覆盖,只是调用Base运算符=:

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 =,我似乎无法找出原因。虚拟运算符有什么特别之处=还是我在做些傻事?

1 个答案:

答案 0 :(得分:3)

您忘记的是,无论您编写什么,您仍然可以获得编译器提供的派生特定副本分配运算符。由于它比基类版本更好匹配,因此调用默认值。