我知道可以在派生类构造函数中调用基类函数,因为基类是在派生类之前构造的。但是我不确定这是否是一种好习惯。示例代码为:
class Base {
public:
int Get() const { return i_; }
void Set(const int i) { i_ = i; }
private:
int i_{0};
};
class Derived : public Base {
// initialize `derived_i_` with a call to base class function, Is this a good
// practice in production code?
Derived() : derived_i_{Get()} {
// do some other things
}
private:
int derived_i_{0};
};
答案 0 :(得分:1)
要更加有趣,可以将构造函数编写如下:
Derived() : Base(), derived_i_{Get()} {
// do some other things
}
在对派生类进行任何初始化之前,编译器应完全构建基类。