为什么纯虚函数初始化为0? [英] Why is a pure virtual function initialized by 0?

查看:41
本文介绍了为什么纯虚函数初始化为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们总是将纯虚函数声明为:

We always declare a pure virtual function as:

virtual void fun () = 0 ;

即,它总是被赋值为 0.

I.e., it is always assigned to 0.

我的理解是,这是为了将此函数的 vtable 条目初始化为 NULL,而此处的任何其他值都会导致编译时错误.这种理解正确与否?

What I understand is that this is to initialize the vtable entry for this function to NULL and any other value here results in a compile time error. Is this understanding correct or not?

推荐答案

使用 =0 的原因是 Bjarne Stroustrup 认为他无法获得另一个关键字,例如pure";在实现该功能时通过了 C++ 社区.这在他的书中有描述,The Design &C++ 的演变,第 13.2.3 节:

The reason =0 is used is that Bjarne Stroustrup didn't think he could get another keyword, such as "pure" past the C++ community at the time the feature was being implemented. This is described in his book, The Design & Evolution of C++, section 13.2.3:

选择了奇怪的 =0 语法...因为当时我看不到机会接受新的关键字.

The curious =0 syntax was chosen ... because at the time I saw no chance of getting a new keyword accepted.

他还明确指出,这不需要将 vtable 条目设置为 NULL,并且这样做并不是实现纯虚函数的最佳方式.

He also states explicitly that this need not set the vtable entry to NULL, and that doing so is not the best way of implementing pure virtual functions.

这篇关于为什么纯虚函数初始化为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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