我有 2 个类,A
和 B
,我需要在 B
中覆盖一个函数,以便从 A
调用code> 的构造函数。这是我已经拥有的:
class A {
A(char* str) {
this->foo();
}
virtual void foo(){}
}
class B : public A {
B(char* str) : A(str) {}
void foo(){
//stuff here isn't being called
}
}
如何从 A::A()
获取要在 B::foo()
中调用的代码?
最佳答案
I need an overwritten function in B to be called from A's constructor
这种设计在 C++ 中是不可能的:order of construction B 对象的构造是首先构造基类 A 子对象,然后在其之上构造 B。
结果是,在 A 构造函数中,你仍然在构造一个 A 对象:此时调用的任何虚函数都将是 A 的虚函数。只有当 A 构造完成并开始构造 B 时,才会B 的虚函数生效。
为了实现您想要的效果,您必须使用两步模式:1) 构建对象,2) 初始化它。
关于C++调用从基类派生的覆盖函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35373328/