在多个 cpp 文件 C++ 上使用类/结构/联合

2022-01-11 00:00:00 class header include struct c++

我正在尝试在 C++ 中创建一个类,并且能够在多个 C++ 文件中访问该类的元素.我已经尝试了超过 7 种可能的解决方案来解决错误,但都没有成功.我研究了类前向声明??,这似乎不是答案(我可能是错的).

I am trying to create a class in C++ and be able to access elements of that class in more than one C++ file. I have tried over 7 possible senarios to resolve the error but have been unsuccessful. I have looked into class forward declaration which doesen't seem to be the answer (I could be wrong).

//resources.h
class Jam{
public:
int age;
}jam;

//functions.cpp
#include "resources.h"
void printme(){
std::cout << jam.age;
}

//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}

Error 1 error LNK2005: "class Jam jam" (?jam@@3VJam@@A) 已在 stdafx.obj 中定义

错误 2 错误 LNK1169:找到一个或多个多重定义符号

我知道错误是多重定义,因为我在两个 CPP 文件中都包含 resources.h.我怎样才能解决这个问题?我尝试在 CPP 文件中声明 class Jam,然后为需要访问该类的每个 CPP 文件声明 extern class Jam jam;.我也尝试过声明指向该类的指针,但没有成功.谢谢!

I understand the error is a multiple definiton because I am including resources.h in both CPP files. How can I fix this? I have tried declaring the class Jam in a CPP file and then declaring extern class Jam jam; for each CPP file that needed to access the class. I have also tried declaring pointers to the class, but I have been unsuccessful. Thank you!

推荐答案

变量jam定义在H文件中,包含在多个CPP类中,有问题.

The variable jam is defined in the H file, and included in multiple CPP classes, which is a problem.

不应在 H 文件中声明变量,以避免发生这种情况.将类定义保留在 H 文件中,但在 CPP 文件的 一个 中定义变量(如果您需要全局访问它 - 在所有休息).

Variables shouldn't be declared in H files, in order to avoid precisely that. Leave the class definition in the H file, but define the variable in one of the CPP files (and if you need to access it globally - define it as extern in all the rest).

例如:

//resources.h
class Jam{
public:
int age;
};
extern Jam jam; // all the files that include this header will know about it

//functions.cpp
#include "resources.h"
Jam jam; // the linker will link all the references to jam to this one
void printme(){
std::cout << jam.age;
}

//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}

相关文章