为什么默认赋值运算符不是从基类运算符的赋值中调用的



通过使用从抽象基类到派生赋值运算符中的动态强制转换来实现带有赋值运算符的派生类,我想调用从派生到派生的赋值运算符。这是有效的。

#include <iostream>
using namespace std;
class base
{
public:
virtual base& operator = (const base& ) = 0;
};
class derived: public base
{
public:
derived (int d): data(d) {};
derived& operator = (const base& b)
{
if (&b == this) return *this;
const derived &d = dynamic_cast<const derived&> (b);
*this = d;
return *this;
}
derived& operator = (const derived& d)
{
if (&d == this) return *this;
data = d.data;
return *this;
}
private:
int data;
};

但是,当我没有明确实现derived& operator = (const derived& d)或使用时

derived& operator = (const derived& d) = default;

编译失败,抱怨"未定义对base::operator=(base const&)的引用"(即试图调用抽象方法(。为什么?有没有办法不实现默认分配?这似乎是多余的,可能会导致未来的错误,例如,在没有相应修改赋值运算符的情况下,将字段添加到基类/派生类中?

如果您想强制派生类D实现函数D::operator=(const base&),您还希望它们能够拥有自己的默认副本分配运算符D::operator=(const D&) = default;,那么:

  • 使base::operator=(const base&)纯净(正如您已经做的那样(,
  • 提供了CCD_ 7的越界定义。这看起来像:base& base::operator= (const base&) = default;base的复制赋值运算符的定义是必需的,因为它将由每个派生类的默认复制赋值运算符调用

这很奇怪,但声明为纯的函数仍然可以提供定义。

最新更新