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

时间:2013-06-26 00:54:05

标签: 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
}

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

2 个答案:

答案 0 :(得分:8)

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

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

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

使用Base的复制构造函数。

答案 1 :(得分:1)

在构造函数中,您应该使用初始化列表:

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

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

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