gpt4 book ai didi

C++ 对一个定义规则的混淆

转载 作者:行者123 更新时间:2023-11-30 01:46:44 24 4
gpt4 key购买 nike

我正在阅读 One Definition Rule .它说:

if one .cpp file defines struct S { int x; }; and the other .cpp filedefines struct S { int y; };, the behavior of the program that linksthem together is undefined. This is usually resolved with unnamednamespaces.

我不明白为什么以及它是如何未定义的?有人会向我解释这背后的真正原因吗?如何用未命名的命名空间解析?

最佳答案

正如它所说的那样。您用不同的定义定义了同一个类 S 两次。语言的创造者已经声明你不应该这样做。原因是允许它显然是荒谬的,并且会破坏翻译单元之间的兼容性。哪个定义是“正确”的?你的编译器应该使用哪个?

未命名的命名空间导致两个定义实际上定义了不同S,它们被恰本地命名为类似于my-anonymous-namespace-1::Smy-anonymous-namespace-2::S,尽管您永远不能那样引用它们,因为命名空间是匿名的。

关于C++ 对一个定义规则的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32700125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com