无法在其抽象类中调用纯虚函数?

时间:2014-07-30 22:43:38

标签: c++

我有一个与此类似的代码:

#include <iostream>

class parent
{
public:
    parent()
    //does initializations here
    {
        start();
    }
    virtual void start()=0;
}

class child :public parent
{
public:
    child()
    {}
    void start()
    {
        std::cout << "starting.." << std::endl;
    }
}

在父类的构造函数中调用start()函数会导致链接错误 (未解析的外部符号)。我认为这不是问题,为什么呢?有没有其他方法,而不是在构建后手动调用start()函数?

1 个答案:

答案 0 :(得分:0)

虚拟调度仅适用于已经构建的对象的部分。在parent的构造函数中,child尚不存在,因此调用start()会调用parent::start

您可以通过以下方式为其提供正文:

void parent::start() {}

虽然要实现child::start的调用,您需要从child的构造函数中调用它。