【发布时间】:2013-06-22 23:49:19
【问题描述】:
我知道对于独立类,您应该避免在复制构造函数中调用赋值运算符。复制和交换以及将重用的代码移动到私有成员函数是轻松重用代码的两种方法。但是,最近我遇到了一个问题。代码如下:
// 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
}
在这个给定的应用程序中,这一切都是有意义的,因为派生类现在可以对它刚刚从基类接收到的成员执行操作以填充对象的其余部分。此外,这为用户提供了一种将基础对象转换为派生对象的安全方式。我似乎缺少的是这样的代码是否是好的代码实践,或者是否有更简单/更好的方法来完成我想要做的事情?正如我之前提到的,我知道从独立类中的复制构造函数调用赋值运算符通常是不可行的,但是从另一个构造函数调用赋值运算符呢?
【问题讨论】:
-
嗯...为什么要避免在复制构造函数中使用赋值运算符?
-
为什么不从派生类构造函数调用基类构造函数,而是通过赋值运算符?
-
看来
Base应该是成员而不是基地...... -
@BillyONEal,我当然明白你的意思。但是,鉴于 base 的实现,有一些封装问题需要解决。也就是说,base 中有一些函数是受保护的,需要在派生中使用,但用户不能真正访问它们,否则他们有机会真正对对象造成一些损害。长篇大论...
标签: c++ inheritance constructor assignment-operator