【发布时间】:2013-05-02 17:53:05
【问题描述】:
有这个代码:
文件 a.hpp:
class A;
文件 a.cpp:
#include "a.hpp"
struct A {
int x = 777;
int y;
};
A a_zew;
文件 main.cpp:
#include "a.hpp"
#include <iostream>
class A { // definition of class A is different than above
public:
int x;
};
int main() {
A a; // definition of class A in main.cpp
extern A a_zew; // definition of class A in a.cpp
std::cout << a_zew.x << std::endl; // 777
std::cout << a.x << std::endl; // junk
return 0;
}
所以A 类在文件main.cpp 和a.cpp 中都定义了,并且在每个翻译单元中还定义了这些类的两个对象。 A 类的两个翻译单元中的定义不同,但此代码可以编译。然而,一个定义规则说程序中可以有许多类型的定义(但每个翻译单元中只有一个)并且这些定义应该相同。那么为什么即使两个文件中类A的定义不同,这段代码也会编译呢?
【问题讨论】:
-
IIRC 这是未定义的行为。所以它可以工作,或者它可能会崩溃,或者它可以向你的母亲发送电子邮件。这些都是调用 UB 的有效结果。
标签: c++