为什么下面的示例会打印“0”以及必须更改什么才能按我的预期打印“1”?
#include <iostream>
struct base {
virtual const int value() const {
return 0;
}
base() {
std::cout << value() << std::endl;
}
virtual ~base() {}
};
struct derived : public base {
virtual const int value() const {
return 1;
}
};
int main(void) {
derived example;
}
最佳答案
因为 base
是首先构建的,并且还没有“成熟”成 derived
。当它不能保证对象已经正确初始化时,它不能调用对象上的方法。
关于来自构造函数的 C++ 虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/496440/