C++ 中的外部结构?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3266580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:28:42  来源:igfitidea点击:

Extern Struct in C++?

c++

提问by Richard Taylor

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 中声明相同的结构,并编译它,但值是错误的。

回答by Alex Martelli

You put the struct MyStructtype declaration in a .hfile 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;
}

回答by Richard Taylor

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. All externdoes 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. If you don't define struct MyStruct theVarsomewhere, it likely won't compile all the way anyways when it reaches the linker.

编辑:某些 .CPP 文件需要包含原始声明。所有extern做的就是告诉编译器/连接信任你它的存在别的地方,程序生成时,它会找到有效的定义。如果您没有在struct MyStruct theVar某处定义,那么当它到达链接器时可能不会一直编译。