C++:在派生类构造函数中调用基类赋值运算符的形式不正确
C++: Bad Form to Call Base Class Asssignment Operator in Derived Class Constructor?
我知道,对于独立类,应该避免在复制构造函数中调用赋值运算符。复制和交换以及将重用的代码移动到私有成员函数是轻松重用代码的两种方法。然而,最近我遇到了一个小问题。这是代码:
// 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);
相关文章:
- 基类和派生类的多态赋值运算符
- 为什么基类中的复制和交换会导致派生类中的复制赋值运算符被隐式删除?
- 禁止复制构造函数和赋值运算符singleton类
- 无法在赋值运算符中访问基类的受保护方法
- 在基中使用派生类的赋值运算符
- 如何使用继承(抽象基类)实现移动构造函数和移动赋值运算符
- 默认赋值运算符有权访问基类的私有成员
- 如何在map中放置具有"deleted"复制ctor和赋值运算符的类?
- 带有赋值运算符的类的C++深度复制
- 将赋值运算符与类实例和向量一起使用
- 如何重载赋值运算符以允许我的类等于基元类型,例如'int'
- 为什么派生类不使用基类运算符=(赋值运算符)?
- 在将抽象基类作为参数的函数中将指针和赋值运算符与派生类一起使用
- 我可以从子类以外的另一个类调用抽象基类的公共赋值运算符吗?
- 使用"using"声明隐藏基类方法不适用于赋值运算符
- 为C++中具有多个继承派生类的vtables的基之一调用赋值运算符
- C++ - 从基类"inherit"重载赋值运算符派生类的安全/标准方法
- 将派生类赋值给基类的更好方法
- 将派生对象赋值给基类对象而不使用对象切片
- 删除被赋值给基类指针的派生类指针