【发布时间】:2016-05-24 05:39:41
【问题描述】:
我有 2 个类,A 和 B,我需要在 B 中覆盖一个函数,以便从 A 的构造函数中调用。这是我已经拥有的:
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() 中调用的代码?
【问题讨论】:
-
不要在构造函数中使用虚函数,在构造B时,先构造A。此时尚未设置 B 的额外方法/变量。所以事情可能会大错特错。
标签: c++ function inheritance polymorphism virtual