C++ 一个定义规则和两个翻译单元中的不同类定义
有以下代码: 文件a.hpp:C++ 一个定义规则和两个翻译单元中的不同类定义,c++,C++,有以下代码: 文件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(
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.hpp”
#包括
A类{//A类的定义与上述不同
公众:
int x;
};
int main(){
A;//main.cpp中类A的定义
extern A_zew;//A.cpp中类A的定义
std::cout您的程序具有未定义的行为。C++11标准第3.2/6段规定:
一个程序中可以有一个以上的类类型定义(第9条),[…],只要每个定义
出现在不同的翻译单元中,前提是定义满足以下要求。给定
这种名为D
的实体定义在多个翻译单元中,然后[…]
下面是您的程序确实违反的要求列表。但是,在列表的末尾,提到了这一点:
[…]如果D
的定义满足所有这些要求,
然后,如果D
的定义不满足要求,则程序的行为应与D
的定义相同
如果满足这些要求,则行为未定义
IIRC这是未定义的行为。所以它可能会工作,也可能会崩溃,也可能会向你母亲发送电子邮件。这些都是调用UB的有效结果。