【问题标题】:struct with same name but different member in C++C ++中具有相同名称但成员不同的结构
【发布时间】:2016-09-09 06:18:31
【问题描述】:

根据 The C++ Programming Language (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

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

【问题讨论】:

  • 我不确定这是否违反了单一定义规则 (ODR)。但是,如果是,编译器不需要给出错误 - 这只是意味着程序员犯了错误。
  • @MartinBonner:是的,这显然违反了 ODR。你说的对。编译器不需要给出错误
  • 请不要插入商业网站的链接。
  • @YvesDaoust。好的,明白了。

标签: c++ c++11 undefined-behavior one-definition-rule


【解决方案1】:

One Definition Rule 说:

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

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

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

希望对您有所帮助。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 2019-10-14
    • 2011-01-24
    相关资源
    最近更新 更多