外部结构?

Ric*_*lor 15 c++

我正在使用extern从另一个类中获取变量,它适用于int,float等...

但这不起作用,我不知道该怎么做:

Class1.cpp

struct MyStruct {
 int x;
}

MyStruct theVar;
Run Code Online (Sandbox Code Playgroud)

Class2.cpp

extern MyStruct theVar;

void test() {
 int t = theVar.x;
}
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为Class2不知道MyStruct是什么.

我该如何解决?:/

我尝试在Class2.cpp中声明相同的结构,并编译,但值是错误的.

Ale*_*lli 25

您将struct MyStruct类型声明放在一个.h文件中,并将其包含在class1.cpp和class2.cpp中.

IOW:

Myst.h

struct MyStruct {
 int x;
};
Run Code Online (Sandbox Code Playgroud)

Class1.cpp

#include "Myst.h"

MyStruct theVar;
Run Code Online (Sandbox Code Playgroud)

Class2.cpp

#include "Myst.h"

extern struct MyStruct theVar;

void test() {
 int t = theVar.x;
}
Run Code Online (Sandbox Code Playgroud)