![](/img/trans.png)
[英]Are classes allowed to have different definitions across different translation units in a program?
[英]Multiple definitions in different translation units
我知道,对于一个定义规则,如果它们具有相同顺序的相同标记,则可以在多个翻译单元中定义一个类,但是此程序对我来说很奇怪
文件main.cpp
#include "Source.h"
struct mystructure
{
int field1;
float field2;
};
int main()
{
mystructure myvar;
myvar.field2= 2.0f;
myCustomFunction(myvar);
return 0;
}
文件Source.h
struct mystructure;
void myCustomFunction(mystructure& vv);
文件Source.cpp
#include "Source.h"
struct mystructure
{
char otherfield;
int anotherone;
bool anotheranotherone;
};
void myCustomFunction(mystructure& vv)
{
vv.otherfield = 'A';
}
我正在使用MSVC2012,编译器没有抱怨。 这是为什么? 那是正常的吗?
编译器很难抱怨,因为在同一编译过程中它从不会看到冲突的声明。 但是这段代码是不正确的,不幸的是,编译器不会发现所有错误,标准也不要求它们这样做。
不用抱怨,因为结构名称实际上并未从翻译单元中导出为符号。 它们仅在编译器内部使用。 因此,即使您定义了两个具有相同名称的结构,也不会出现链接器错误。
但是,由于结构不匹配,您将获得未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.