c ++:从基础构造函数调用derrived函数?

时间:2010-07-02 14:18:09

标签: c++ inheritance

  

可能重复:
  Calling virtual functions inside constructors

class Base
    {
    virtual void method()
        { cout << "Run by the base."; };
    public:
    Base() { method(); };
    };

class Derived: public Base
    {
    void method()
        { cout << "Run by the derived."; };
    };

void main()
    {
    Derived();
    }

输出:

Run by the base.

如何在不创建派生构造函数的情况下运行派生方法?

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

你不能因为对象的“派生”部分尚未构造,所以从中调用成员函数将是未定义的行为。

答案 2 :(得分:1)

如果不添加额外代码,则无法执行此操作。

实现此目的的常用方法是使用私有构造函数和create函数,该函数首先调用构造函数(通过new),然后使用新创建的第二个finish_init方法宾语。这确实可以防止您在堆栈上创建对象的实例。