从构造函数调用虚函数和纯虚函数

编程入门 行业动态 更新时间:2024-10-27 02:23:34
本文介绍了从构造函数调用虚函数和纯虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我从基础构造函数调用虚函数时,编译器不会给出任何错误。但是当我从基类构造函数调用一个纯虚函数时,它会给出编译错误。

When i invoke a virtual function from a base constructor, the compiler does not give any error. But when i invoke a pure-virtual function from the base class constructor, it gives compilation error.

考虑下面的示例程序:

#include <iostream> using namespace std; class base { public: void virtual virtualfunc() = 0; //void virtual virtualfunc(); base() { virtualfunc(); } }; void base::virtualfunc() { cout << " pvf in base class\n"; } class derived : public base { public: void virtualfunc() { cout << "vf in derived class\n"; } }; int main() { derived d; base *bptr = &d; bptr->virtualfunc(); return 0; }

这里可以看出纯虚函数有一个定义。我希望在执行 bptr-> virtualfunc()时调用基类中定义的纯虚函数。相反,它给出编译错误:

Here it is seen that the pure virtual function has a definition. I expected the pure virtual function defined in base class to be invoked when bptr->virtualfunc() is executed. Instead it gives the compilation error:

错误:abstract virtual`virtual void base :: virtualfunc

error: abstract virtual `virtual void base::virtualfunc()' called from constructor

原因是什么?

推荐答案

不要从构造函数中调用纯虚函数,因为它会导致未定义行为。

C ++ 03 10.4 / 6个状态

成员函数可以从抽象类的构造函数对于正在从这样的构造函数(或析构函数)创建(或销毁)的对象,直接或间接地对一个纯虚拟函数进行虚拟调用(10.3)是未定义的。

"Member functions can be called from a constructor (or destructor) of an abstract class; the effect of making a virtual call (10.3) to a pure virtual function directly or indirectly for the object being created (or destroyed) from such a constructor (or destructor) is undefined."

您得到一个编译错误,因为您没有在Base类中定义纯虚函数 virtualfunc()。为了能够调用它,它必须有一个body。

You get an compilation error because you have not defined the pure virtual function virtualfunc() in the Base class. To be able to call it, it must have an body.

无论如何,在构造函数中调用纯虚函数应该被避免,因为它是未定义的行为。

Anyways, calling pure virtual functions in constructors should be avoided as it is Undefined Behavior to do so.

更多推荐

从构造函数调用虚函数和纯虚函数

本文发布于:2023-06-12 05:21:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/652118.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!