繁体   English   中英

C++ 中的外部结构?

[英]Extern Struct in C++?

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

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

类1.cpp

struct MyStruct {
 int x;
}

MyStruct theVar;

类2.cpp

extern MyStruct theVar;

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

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

我该如何解决?

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

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

爱荷华州:

Myst.h

struct MyStruct {
 int x;
};

类1.cpp

#include "Myst.h"

MyStruct theVar;

类2.cpp

#include "Myst.h"

extern struct MyStruct theVar;

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

您需要首先在类或公共头文件中定义您的结构。 例如,确保通过#include "Class1.h"包含此初始定义。

然后,您需要修改您的语句以说extern struct MyStruct theVar;

该语句不需要在头文件中。 它可以是全球性的。

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

暂无
暂无

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

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