我已阅读以下资料:
https://www.wikiwand.com/en/One_Definition_Rule
http://en.cppreference.com/w/cpp/language/definition
What is the difference between a definition and a declaration?
但是还是不明白为什么是One Definition Rule而不是One Declaration Rule?
我认为声明是定义的子集,因此一个定义规则就足够了。
最佳答案
一个声明规则会过于严格,会阻止多次使用同一 header 的程序进行编译。这也使得无法使用反向引用定义数据结构。
查看第一点(使用标题)的一个简单方法是考虑一个由两个翻译单元组成的程序,A.cpp
和 B.cpp
, 其中都包括 <string>
标题。
翻译单元 A.cpp
和 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
来自 struct node *tree
未声明。切换 struct node
的顺序和 struct tree
声明无济于事,因为那样tree
来自 struct tree *owner
将未声明。 C 和 C++ 中唯一的解决方案是为两个 struct
中的任何一个引入第二个声明。
关于c++ - 为什么一个定义规则,而不是一个声明规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46988095/