C ++对一个定义规则的困惑 [英] C++ confusion about one definition rule

查看:112
本文介绍了C ++对一个定义规则的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关> 一个定义规则 .它说:

I was reading about One Definition Rule. It says that:

如果一个.cpp文件定义了 struct S {int x; }; 和其他.cpp文件 定义 struct S {int y; }; ,链接程序的行为 它们在一起是不确定的.通常用未命名解决 命名空间.

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

我不明白为什么&怎么是不确定的?有人能解释一下这背后的真正原因吗?如何使用未命名的名称空间解决它?

I don't understand why & how it is undefined? Will someone explain me the actual reason behind this? How it is resolved with unnamed namespaces?

推荐答案

就像它说的那样.您使用不同的定义两次定义了相同的类S.语言的创造者已经宣布您不应这样做.原因是,允许这样做显然是荒谬的,并会导致跨翻译单位的兼容性遭到破坏. 正确"的定义是哪个?您的编译器应该使用哪个?

It's just as it says. You defined the same class S twice, with different definitions. The makers of the language have declared that you shall not do this. The reason is that allowing it would be clearly nonsensical, and result in breaking compatibility across your translation units. Which definition is the "right" one? Which should your compiler use?

一个未命名的命名空间会导致两个定义实际上定义了不同S,这些类被正确命名为类似于my-anonymous-namespace-1::Smy-anonymous-namespace-2::S的名称,尽管您永远无法像这样引用它们因为命名空间是匿名的.

An unnamed namespace results in the two definitions actually defining different classes S, which are properly named something akin to my-anonymous-namespace-1::S and my-anonymous-namespace-2::S, though you can never refer to them like that because the namespaces are, well, anonymous.

这篇关于C ++对一个定义规则的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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