简体   繁体   English

C++ 中的外部结构?

[英]Extern Struct in C++?

I'm using extern to fetch variables from another class, and it works fine for int's, float's etc...我正在使用 extern 从另一个类中获取变量,它适用于 int、float 等......

But this doesn't work, and I don't know how to do it:但这不起作用,我不知道该怎么做:

Class1.cpp类1.cpp

struct MyStruct {
 int x;
}

MyStruct theVar;

Class2.cpp类2.cpp

extern MyStruct theVar;

void test() {
 int t = theVar.x;
}

It doesn't work because Class2 doesn't know what MyStruct is.它不起作用,因为 Class2 不知道 MyStruct 是什么。

How do I fix this?我该如何解决?

I tried declaring the same struct in Class2.cpp, and it compiled, but the values were wrong.我尝试在 Class2.cpp 中声明相同的结构,并编译它,但值是错误的。

You put the struct MyStruct type declaration in a .h file and include it in both class1.cpp and class2.cpp.您将struct MyStruct类型声明放在.h文件中,并将其包含在 class1.cpp 和 class2.cpp 中。

IOW:爱荷华州:

Myst.h Myst.h

struct MyStruct {
 int x;
};

Class1.cpp类1.cpp

#include "Myst.h"

MyStruct theVar;

Class2.cpp类2.cpp

#include "Myst.h"

extern struct MyStruct theVar;

void test() {
 int t = theVar.x;
}

You need to first define your struct in a class or common header file.您需要首先在类或公共头文件中定义您的结构。 Make sure you include this initial definition by means of #include "Class1.h" for instance.例如,确保通过#include "Class1.h"包含此初始定义。

Then, you need to modify your statement to say extern struct MyStruct theVar;然后,您需要修改您的语句以说extern struct MyStruct theVar;

This statement does not need to be in a header file.该语句不需要在头文件中。 It can be global.它可以是全球性的。

Edit: Some .CPP file needs to contain the original declaration.编辑:某些 .CPP 文件需要包含原始声明。 All extern does is tell the compiler/linker to trust you that it exists somewhere else and when the program is built, it will find the valid definition. extern所做的就是告诉编译器/链接器相信你它存在于其他地方,并且当程序构建时,它会找到有效的定义。 If you don't define struct MyStruct theVar somewhere, it likely won't compile all the way anyways when it reaches the linker.如果您没有在某处定义struct MyStruct theVar ,那么当它到达链接器时,它可能不会一直编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM