[英]One definition rule and different class definitions in two translation units
There is this code:有这个代码:
file a.hpp:文件a.hpp:
class A;
file a.cpp:文件 a.cpp:
#include "a.hpp"
struct A {
int x = 777;
int y;
};
A a_zew;
file main.cpp:文件 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;
}
So class A
is defined both in file main.cpp and a.cpp and there are also two objects of these classes defined in each translation unit.所以类
A
在文件main.cpp和a.cpp 中都定义了,并且在每个翻译单元中也定义了这些类的两个对象。 Definition in both translation units of class A
is different but this code compiles. A
类的两个翻译单元中的定义不同,但此代码可以编译。 However one definition rule says that there can be many definitions of the type in the program (but only single in each translation unit) and these definitions should be the same.然而,一个定义规则说程序中可以有多个类型的定义(但在每个翻译单元中只有一个)并且这些定义应该是相同的。 So why does this code compile even if definition of class
A
is different in both files?那么为什么即使两个文件中类
A
定义不同,这段代码也会编译?
There is this code:有这个代码:
file a.hpp:文件a.hpp:
class A;
file a.cpp:文件 a.cpp:
#include "a.hpp"
struct A {
int x = 777;
int y;
};
A a_zew;
file main.cpp:文件 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;
}
So class A
is defined both in file main.cpp and a.cpp and there are also two objects of these classes defined in each translation unit.所以类
A
在文件main.cpp和a.cpp 中都定义了,并且在每个翻译单元中也定义了这些类的两个对象。 Definition in both translation units of class A
is different but this code compiles. A
类的两个翻译单元中的定义不同,但此代码可以编译。 However one definition rule says that there can be many definitions of the type in the program (but only single in each translation unit) and these definitions should be the same.然而,一个定义规则说程序中可以有多个类型的定义(但在每个翻译单元中只有一个)并且这些定义应该是相同的。 So why does this code compile even if definition of class
A
is different in both files?那么为什么即使两个文件中类
A
定义不同,这段代码也会编译?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.