在多个cpp文件C ++中使用类/ struct / union [英] Using a class/struct/union over multiple cpp files C++

查看:341
本文介绍了在多个cpp文件C ++中使用类/ struct / union的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C ++中创建一个类,并且能够在多个C ++文件中访问该类的元素。我已经尝试超过7可能的方案来解决错误,但已经失败。

  //资源(我可能是错误的) .h 
class Jam {
public:
int age;
} jam;

//functions.cpp
#includeresources.h
void printme(){
std :: cout<堵塞
}

//main.cpp
#includeresources.h
int main(){
printme();
std :: cout<<堵塞
}

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



错误2错误LNK1169:one或更多的多重定义符号



我理解错误是多重定义,因为我包括 resources.h 。如何解决这个问题?我试着在CPP文件中声明 class Jam ,然后为每个CPP文件声明 extern class Jam jam; 需要访问类。我也试过声明指向类的指针,但我没有成功。谢谢!

解决方案

变量 jam ,并且包含在多个CPP类中,这是一个问题。



变量不应该在H文件中声明,以避免这种情况。在H文件中保留类定义,但在CPP文件的一个中定义变量(如果您需要全局访问它,请将其定义为 extern

  // resources.h 
class Jam {
public:
int age;
};
extern果酱酱//包含此标题的所有文件都会知道它

//functions.cpp
#includeresources.h
Jam jam; //链接器将链接所有对jam的引用
void printme(){
std :: cout<堵塞
}

//main.cpp
#includeresources.h
int main(){
printme();
std :: cout<<堵塞
}


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) already defined in stdafx.obj

Error 2 error LNK1169: one or more multiply defined symbols found

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!

解决方案

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

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).

For example:

//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 ++中使用类/ struct / union的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆