因此,调用父类构造函数的普通方法是在初始化列表中:
e.g.
#include <cstdio>
struct Parent {
explicit Parent(int a) {
printf("Parent -- int\n");
}
};
struct Child : public Parent {
explicit Child(int a) : Parent(1) {
printf("Child -- int\n");
}
};
int main(int argc, char **argv) {
Child c = Child(10);
};
prints Parent -- int
then Child -- int
.
(某种程度上)不管这是否是一个好主意,我想知道是否可以在初始化列表之外的构造函数主体中(在正在构造的对象上)显式调用父构造函数。
不,不是按照您想要的方式,因此它构造了对象的父部分。
处理这种情况的常见方法是使用“init”或“construct”方法,然后可以从子构造函数调用它们:
struct Parent {
explicit Parent(int a) {
Construct(a);
}
protected:
void Construct(int a) { printf("Parent -- int\n"); }
Parent() {}
};
struct Child : public Parent {
explicit Child(int a) {
Parent::Construct(a);
printf("Child -- int\n");
}
};
int main(int argc, char **argv) {
Child c = Child(10);
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)