C++:在派生类构造函数中调用基类分配运算符的错误表单?

It'*_*ete 0 c++ inheritance constructor assignment-operator

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

// 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
}
Run Code Online (Sandbox Code Playgroud)

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

asc*_*ler 8

Derived::Derived(const Base& base) {
  *this = base;
}
Run Code Online (Sandbox Code Playgroud)

此默认值构造Base构造Derived对象中的子对象,然后分配它.您可能会做得更好:

Derived::Derived(const Base& base)
  : Base(base)
{
}
Run Code Online (Sandbox Code Playgroud)

它使用的复制构造函数Base.