gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:35:25 25 4
gpt4 key购买 nike

根据 The C++ Programming Language (Bjarne Stroustrup) 一书,第 15.2.3 节(唯一定义规则)第 425 页,我编写的程序如下:

文件1.cpp

struct S2 { int a; char b; };

文件2.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

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

最佳答案

One Definition Rule说:

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.

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

如果您想知道背后的原因,请阅读 this .

希望对您有所帮助。 :)

关于c++ - C++中具有相同名称但成员不同的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203432/

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