Gio*_*hal 57 c++ oop virtual constructor class
为什么以下示例打印"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;
}
Run Code Online (Sandbox Code Playgroud)
Sea*_*ght 90
因为base是先建造而且还没有"成熟" derived.当它无法保证对象已经正确初始化时,它无法调用对象上的方法.
CB *_*ley 20
在构造派生对象时,在调用派生类构造函数的主体之前,必须完成基类构造函数.在调用派生类构造函数之前,构造中的对象的动态类型是基类实例而不是派生类实例.因此,从构造函数调用虚函数时,只能调用基类虚函数覆盖.
实际上,有一种方法可以获得这种行为."软件中的每个问题都可以通过一定程度的间接解决."
/* Disclaimer: I haven't done C++ in many months now, there might be a few syntax errors here and there. */
class parent
{
public:
parent( ) { /* nothing interesting here. */ };
protected:
struct parent_virtual
{
virtual void do_something( ) { cout << "in parent."; }
};
parent( const parent_virtual& obj )
{
obj.do_something( );
}
};
class child : public parent
{
protected:
struct child_virtual : public parent_virtual
{
void do_something( ) { cout << "in child."; }
};
public:
child( ) : parent( child_virtual( ) ) { }
};
Run Code Online (Sandbox Code Playgroud)