C++ - virtual operator= 从 Derived 实例在 Base class 上被调用?
C++ - virtual operator= being called on Base class from Derived instance?
我在覆盖 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= 有什么特别之处还是我在做一些愚蠢的事情?
您忘记的是,无论您编写了什么,您仍然会得到编译器提供的特定于派生的复制赋值运算符。由于它比基础-class 版本更匹配,因此调用默认版本。
我在覆盖 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= 有什么特别之处还是我在做一些愚蠢的事情?
您忘记的是,无论您编写了什么,您仍然会得到编译器提供的特定于派生的复制赋值运算符。由于它比基础-class 版本更匹配,因此调用默认版本。