纯虚函数是那些具有纯说明符 ( = 0;
) 的成员函数
C++03 的 Clause 10.4 paragraph 2 告诉我们什么是抽象类,并附注如下:
[注意:函数声明不能同时提供纯说明符和定义 —尾注] [示例:
struct C {
virtual void f() = 0 { }; // ill-formed
};
——结束示例]
对于那些不是很熟悉这个问题的人,请注意纯虚函数可以有定义但是上面提到的条款禁止这样的定义出现在行内(类里面的词汇)。 (对于定义纯虚函数的用途,您可能会看到,例如 this GotW )
现在对于所有其他种类和类型的函数,允许提供类内定义,乍一看,这种限制似乎绝对是人为的和莫名其妙的。仔细想想,第二眼和随后的眼光似乎是这样 :) 但我相信,如果没有特定原因,就不会存在限制。
我的问题是:有人知道那些具体原因吗? 好的也欢迎猜测。
注释:
- MSVC 确实允许 PVF 具有内联定义。所以不要感到惊讶:)
- 这个问题中的单词
inline
不是指inline 关键字。它应该表示lexically in-class
最佳答案
在 SO 线程中 "Why is a pure virtual function initialized by 0?" Jerry Coffin 引用了 Bjarne Stroustrup 的 The Design & Evolution of C++ ,第 §13.2.3 节,我在其中添加了一些我认为相关的部分的强调:
The curious
=0
syntax was chosen over the obvious alternative of introducing a new keyword pure or abstract because at the time I saw no chance of getting a new keyword accepted. Had I suggested pure, Release 2.0 would have shipped without abstract classes. Given a choice between a nicer syntax and abstract classes, I chose abstract classes. Rather than risking delay and incurring the certain fights over pure, I used the tradition C and C++ convention of using 0 to represent "not there." The=0
syntax fits with my view that a function body is the initializer for a function and also with the (simplistic, but usually adequate) view of the set of virtual functions being implemented as a vector of function pointers. [ … ]
因此,在选择语法时,Bjarne 将函数体视为声明符的一种初始化器部分,而将 =0
视为初始化器的另一种形式,表示“无函数体” (或者用他的话来说,“不存在”)。
按理说,在那个概念图中,一个人不能既表示“不在那里”又拥有一个 body 。
或者,仍然是那个概念图,有两个初始化器。
现在,就我的心灵感应能力、google-foo 和软推理而言。我猜想没有人有足够的兴趣™ 向委员会提出关于取消这种纯粹的句法限制并跟进所有随之而来的工作的建议。所以还是那样。
关于c++ - 纯虚函数可能没有内联定义。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39468199/