为什么下面的示例打印"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;
}发布于 2009-01-30 17:41:03
因为base是先构造的,还没有“成熟”成derived。当它不能保证对象已经正确初始化时,它不能调用对象上的方法。
发布于 2009-01-30 17:43:23
在构造派生对象时,必须先完成基类构造函数,然后才能调用派生类构造函数的主体。在调用派生类构造函数之前,正在构造的对象的动态类型是基类实例,而不是派生类实例。因此,当从构造函数调用虚函数时,只能调用基类虚函数重写。
发布于 2009-01-31 08:07:11
实际上,有一种方法可以获得这种行为。“软件中的每个问题都可以通过一定程度的间接解决。”
/* 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( ) ) { }
};https://stackoverflow.com/questions/496440
复制相似问题