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

标签 c++ inheritance constructor assignment-operator

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

// 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)
{
}

它使用了 Base 的复制构造函数。

关于C++:在派生类构造函数中调用基类赋值运算符的形式不正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17309912/

相关文章:

c++ - 声明 d3ddevice 全局或传递到需要它的类中?

c++ - 在模板派生类中复制构造函数

Java:继承和声明

function - 使用 Swift 结构构造函数作为函数

c# - 设置变量 - 构造函数/获取/设置 C#

c# - C++ 后端与 C# 前端?

c++ - 关于字符串迭代器的问题

c++ - 为什么许多 VM 看起来具有 C++ 功能却用 C 编写?

inheritance - 在列表上下文中使用kotlin类扩展时,解析父类的值而不是子类的值

c++ - 解构const指针?