内部和外部结构的符号冲突,C ++对C [英] Symbol clashing of inner and outer structs, C++ vs C
问题描述
所以,说我有以下的C ++头, testheader.h
:
So, say I have the following C++ header, testheader.h
:
struct mystruct
{
struct myinnerstruct
{
int x;
} astruct;
};
struct myinnerstruct
{
int x;
};
和下面的C ++源代码, TEST.CPP
:
and the following C++ source, test.cpp
:
#include "testheader.h"
using namespace std;
int main()
{
return 0;
}
G ++编译/链接中给出了没有问题。
g++ gives no issues during compile/link.
现在,如果我有相同的标题,但而不是C ++源,C源文件 test.c以
:
Now, if I have the same header, but instead of the C++ source, a C source file test.c
:
#include "testheader.h"
int main()
{
return 0;
}
和我用gcc编译,我得到以下错误:
And I compile with gcc, I get the following error:
error: redefinition of struct myinnerstruct
所以,我推测,C版的范围是翻译单元,以及C ++版本块范围?有人可以证实这一点的话,也许给我一个理由,为什么它是有道理的?我在做C和C ++ code的一些混合,这是给我了不少麻烦。
So, I gather that the scope of the C version is the translation unit, and the C++ version is block scoped? Can someone confirm this is the case, and maybe give me a reason of why it makes sense? I'm doing some mixing of C and C++ code, and this is giving me quite a bit of trouble.
任何了解大大AP preciated。谢谢!
Any insight is greatly appreciated. Thanks!
推荐答案
在C语言中嵌套的结构实际上并不住在他们父母的范围。然而,在C ++中,他们做 - teststruct :: innerstruct
是一个不同类型 innerstruct
。这是提高在C ++中code封装。如果没有这个规则,没有两个类型相同的命名空间可以定义一个嵌套的迭代器
类,例如,这将是极其恶劣的。
In C nested structs do not actually live in their parents scope. However in C++ they do- teststruct::innerstruct
is a different type to innerstruct
. This is to improve encapsulation in C++ code. Without this rule, no two types in the same namespace could define a nested iterator
class, for example, which would be extremely bad.
ç在对待很多其他很无聊的方式结构,所以它是毫不奇怪,他们在这里做了错误的事情。不过,C否则不容许类型范围和这里有一个健全的规则将最终推出了许多额外的概念的语言 - ,这将需要引进命名
取值,由于某种原因一直没有完成。
C treats structs in plenty of other very silly ways, so it's no surprise that they did the wrong thing here. However, C does not otherwise allow type scoping and having a sane rule here would have introduced many additional concepts to the language- ultimately, it would have required the introduction of namespace
s, which for some reason was never done.
这篇关于内部和外部结构的符号冲突,C ++对C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!