2

我知道对于一个定义规则,如果它们以相同的顺序具有相同的标记,我可以在多个翻译单元中定义一个类,但是这个程序对我来说很奇怪

文件main.cpp

#include "Source.h"

struct mystructure
{
    int field1;
    float field2;
};

int main()
{

    mystructure myvar;
    myvar.field2= 2.0f;

    myCustomFunction(myvar);

    return 0;
}

文件来源.h

struct mystructure;

void myCustomFunction(mystructure& vv);

文件源.cpp

#include "Source.h"

struct mystructure
{
    char otherfield;
    int anotherone;
    bool anotheranotherone;
};

void myCustomFunction(mystructure& vv)
{
    vv.otherfield = 'A';
}

我正在使用 MSVC2012,编译器没有抱怨。这是为什么?这正常吗?

4

2 回答 2

3

编译器很难抱怨,因为它在同一次编译期间从来没有看到冲突的声明。但是这段代码是不正确的,不幸的是编译器不会发现每一个错误,标准也没有要求他们这样做。

于 2013-05-04T16:53:17.923 回答
2

它不会抱怨,因为结构名称实际上并未作为符号从翻译单元导出。它们仅在编译器内部使用。因此,即使您定义了两个具有相同名称的结构,也不会出现链接器错误。

但是,由于结构不匹配,您将获得未定义的行为。

于 2013-05-04T16:51:06.090 回答