Using a class/struct/union over multiple cpp files C++(在多个 cpp 文件 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;
}
这篇关于在多个 cpp 文件 C++ 上使用类/结构/联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在多个 cpp 文件 C++ 上使用类/结构/联合
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
