我已阅读以下材料:
https://www.wikiwand.com/en/One_Definition_Rule https://www.wikiwand.com/en/One_Definition_Rule
http://en.cppreference.com/w/cpp/language/definition http://en.cppreference.com/w/cpp/language/definition
定义和声明有什么区别? https://stackoverflow.com/questions/1410563/what-is-the-difference-between-a-definition-and-a-declaration
但仍然不明白为什么它是“一种定义规则”而不是“一种声明规则”?
我认为声明是定义的子集,所以一种定义规则足够。
一种声明规则过于严格,会阻止多次使用同一标头的程序进行编译。它还使得无法使用反向引用来定义数据结构。
查看第一点(使用标题)的一个简单方法是考虑由两个翻译单元组成的程序,A.cpp
and B.cpp
,两者都包括<string>
header.
翻译单位A.cpp
and B.cpp
均独立翻译。通过包括<string>
,两个翻译单元都获得声明std::string
.
至于第二点(具有反向引用的数据结构),考虑一个定义树的示例,其中每个节点都有对其父树的反向引用:
// Does not compile
struct tree {
struct node *root;
};
struct node {
struct node *left;
struct node *right;
struct tree *owner;
};
这个例子无法编译,因为node
from struct node *tree
未声明。切换顺序struct node
and struct tree
声明没有帮助,因为那时tree
from struct tree *owner
将是未声明的。 C 和 C++ 中唯一的解决方案是为两者之一引入第二个声明struct
s.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)