C ++需要你从它的派生类初始化基类成员吗? [英] Does C++ require you to initialize base class members from its derived class?
本文介绍了C ++需要你从它的派生类初始化基类成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class Base {
public:
int a;
Base():a(0) {}
virtual ~Base();
}
class Derived : public Base {
public:
int b;
Derived():b(0) {
Base* pBase = static_cast<Base*>(this);
pBase->Base();
}
~Derived();
}
是否需要调用基类构造函数,还是c ++会自动执行此操作吗?例如
C ++要求你从任何派生类初始化基类成员?
Is the call to the base class constructor necessary or does c++ do this automatically? e.g. Does C++ require you to initialize base class members from any derived class?
推荐答案
基类的构造函数会自动在派生类的构造函数被调用之前调用。
The base class's constructor will automatically be called before the derived class's constructor is called.
您可以使用初始化列表明确指定要调用的基础构造函数(如果有多个):
You can explicitly specify which base constructor to call (if it has multiple) using initialization lists:
class Base {
public:
int a;
Base():a(0) {}
Base(int a):a(a) {}
};
class Derived {
public:
int b;
Derived():Base(),b(0) {}
Derived(int a):Base(a),b(0) {}
};
这篇关于C ++需要你从它的派生类初始化基类成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文