在构造函数中调用纯虚函数会产生错误 [英] Calling pure virtual function in constructor gives an error

查看:234
本文介绍了在构造函数中调用纯虚函数会产生错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class a //my base class
 {
public:
    a()
    {
        foo();
    }
  virtual void foo() = 0;
};



class b : public a
{
    public:
    void foo()
    {
    }
};

int main()
{
    b obj; //ERROR:  undefined reference to a::foo()
}

我错误?定义纯虚拟foo。我需要改变我的代码,使其工作?

Why it gives me error? The pure virtual foo is defined. What do I need to change in my code to make it work? I need pure virtual method from base class be called in its constructor.

推荐答案

在构造函数中调用虚函数是被认为是一件不好的事情。

Calling virtual functions in a constructor is recognised as a bad thing to do.


在派生类对象的基类构造期间,对象的类型
是基类的类型。不仅虚拟函数
解析到基类,而且语言的部分使用运行时
类型信息(例如dynamic_cast(参见项目27)和typeid)将
对象视为一个基类类型。

During base class construction of a derived class object, the type of the object is that of the base class. Not only do virtual functions resolve to the base class, but the parts of the language using runtime type information (e.g., dynamic_cast (see Item 27) and typeid) treat the object as a base class type.

所以你的实例化 b 调用 a 构造函数。调用 foo(),但它是 foo() a 被调用。而且(当然)是未定义的。

So your instantiation of b invokes the a constructor. That calls foo(), but it's the foo() on a that gets called. And that (of course) is undefined.

这篇关于在构造函数中调用纯虚函数会产生错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆