繁体   English   中英

具有相同名称但在C ++中具有不同成员的结构

[英]struct with same name but different member in C++

按照书中的C ++编程语言 (Bjarne Stroustrup),在第15.2.3节(一个定义规则)第425页,我编写如下程序:

file1.cpp

struct S2 { int a; char b; };

file2.cpp

struct S2 { int a; char bb; };
int main(){ return 0;}

编译我试过下面的命令。

g++ -std=c++11 file1.cpp file2.cpp

clang++ -std=c++11 file1.cpp file2.cpp

这两个命令都生成可执行文件,没有任何错误或警告。 但是按照书中这个例子应该给出错误。

一个定义规则说:

如果一个.cpp文件定义struct S { int x; }; struct S { int x; }; 另一个.cpp文件定义struct S { int y; }; struct S { int y; }; ,将它们链接在一起的程序的行为是未定义的

因此,您的程序调用未定义的行为(UB)。 因此,编译器不需要为此进行诊断。

如果你想知道背后的原因,那就读一下

希望能帮助到你。 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM