C++:在派生类构造函数中调用基类赋值运算符的形式不正确

C++: Bad Form to Call Base Class Asssignment Operator in Derived Class Constructor?

本文关键字:赋值运算符 基类 不正确 调用 派生 构造函数 C++      更新时间:2023-10-16

我知道,对于独立类,应该避免在复制构造函数中调用赋值运算符。复制和交换以及将重用的代码移动到私有成员函数是轻松重用代码的两种方法。然而,最近我遇到了一个小问题。这是代码:

// Derived.h
class Derived : Base {
  // bunch of fun stuff here
  // ...
  // constructor that builds a derived object from a base one
  explicit Derived(const Base& base);
  // Assignment operator for moving base class member variables into the derived one
  Derived& operator=(const Base& base);
};
// Derived.cpp
Derived::Derived(const& Base base) {
  *this = base; // use assignment operator from derived to base
}
Derived& Derived::operator=(const Base& base) {
  static_cast<Base>(*this) = base;  // call base class assignment operator
}

在这个给定的应用程序中,这一切实际上都是有意义的,因为派生类现在可以对刚从基类接收到的成员执行操作,以填充对象的其余部分。此外,这为用户将基础对象转换为派生对象提供了一种安全的方式。我似乎缺少的是这样的代码是否是良好的代码实践,或者是否有一种更简单/更好的方法来完成我想要做的事情?正如我之前提到的,我知道在独立类中从复制构造函数调用赋值运算符通常是不可行的,但从另一个构造函数调用赋值操作符呢?

Derived::Derived(const Base& base) {
  *this = base;
}

这个默认值在构造的Derived对象中构造Base子对象,然后分配它

Derived::Derived(const Base& base)
  : Base(base)
{
}

其使用CCD_ 3的复制构造函数。

在构造函数中,您应该使用初始值设定项列表:

Derived::Derived(const Base& base) : Base(base) {}

如果你真的想在某个地方重新分配你的基本切片,你只需要显式地调用已经存在的op=:

*this = Base::operator=(base);