【问题标题】:Extern Struct in C++?C ++中的外部结构?
【发布时间】:2019-12-10 23:07:05
【问题描述】:

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

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

Class1.cpp

struct MyStruct {
 int x;
}

MyStruct theVar;

Class2.cpp

extern MyStruct theVar;

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

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

我该如何解决这个问题?

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

【问题讨论】:

    标签: c++


    【解决方案1】:

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

    IOW:

    Myst.h

    struct MyStruct {
     int x;
    };
    

    Class1.cpp

    #include "Myst.h"
    
    MyStruct theVar;
    

    Class2.cpp

    #include "Myst.h"
    
    extern struct MyStruct theVar;
    
    void test() {
     int t = theVar.x;
    }
    

    【讨论】:

    • 结构的定义也应该在标题中吗?还是可以将定义拆分为源 .cpp?
    【解决方案2】:

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

    然后,你需要修改你的语句为extern struct MyStruct theVar;

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

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

    【讨论】:

    • 这足以告诉编译器MyStruct 存在,但是一旦你尝试访问任何成员就会失败。
    猜你喜欢
    • 2020-02-16
    • 2012-07-25
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多