两个类包含彼此的成员
Two classes contaoin members of each other
我有两个类:User.h和Room.h,它们都包含指向另一个类(用户到房间和房间到用户)的对象的指针。我想我知道如何包含.h文件,但我的.cpp一个文件(user.cpp)中仍然有错误。
用户.h
#ifndef USER_H
#define USER_H
class Room;
using namespace std;
class User
{
private:
Room* _currRoom;
public:
//some functions...
};
#endif
room.h
#ifndef ROOM_H
#define ROOM_H
#include "User.h"
class Room
{
private:
vector<User*> _users;
User* _admin;
int _maxUsers;
int _questionTime;
int _questionsNo;
string _name;
int _id;
public:
Room(int id, User* admin, string name, int maxUsers, int questionsNo,int questionTime);
//more functions...
};
#endif
我在room.cpp中包含了user.h,在user.cpp中包含了room.h我的所作所为有什么问题?
在room.h
中,将#include "User.h"
替换为正向声明。在.h
文件中使用正向声明,并将相应的#include
语句移动到.cpp
文件:
user.h
#ifndef USER_H
#define USER_H
class Room;
using namespace std;
class User
{
private:
Room* _currRoom;
public:
//some functions...
};
#endif
user.cpp
#include "user.h"
#include "room.h"
...
房间.h
#ifndef ROOM_H
#define ROOM_H
#include <vector>
#include <string>
class User;
class Room
{
private:
vector<User*> _users;
User* _admin;
int _maxUsers;
int _questionTime;
int _questionsNo;
string _name;
int _id;
public:
Room(int id, User* admin, string name, int maxUsers, int questionsNo, int questionTime);
//more functions...
};
#endif
房间.cpp
#include "room.h"
#include "user.h"
...
如果你不以这种方式进行正向声明,你可能会陷入一种循环的情况,即一个标头通过另一个标头间接包含它自己(a包括B,其中包括a),因此它的标头保护已经被定义,阻止它的声明被处理,从而导致错误。
相关文章:
- 包含作为成员C++函数的结构数组
- 如果包含引用成员的类中缺少原始变量,为什么它仍然可以访问?
- C 函数调用包装器包含类成员功能作为模板参数
- 包含指针成员的嵌套结构
- 在 C++11 中创建并返回包含 lambda 成员变量的类
- 当通过引用传递包含指针成员的类对象时,为什么要多次调用析构函数?我该如何更正
- "static const char array"可以在 C 语言上包含变量成员吗
- 深度复制包含引用成员(C++)的结构
- 如何使用"is_member_function_pointer"在算法中包含/排除成员函数调用
- 当对象包含指针成员时,堆栈上的对象销毁出现分段错误
- 包含指向成员的指针的内联成员初始值设定项
- 对象必须包含指针成员才能与其他对象通信
- 复制包含STL成员(如vector)的C++结构的最佳方法是什么
- 复制包含原子成员的对象的地址
- C++ 派生类的构造函数,其中基类包含类成员
- 当基类不包含数据成员时,虚拟继承是否仍然是必要的
- C++调用没有循环包含的成员函数
- 用包含const成员的结构体实例替换堆栈与静态变量
- 包含unordered_map成员的结构体的Sizeof()方法
- C++ 访问包含此成员的对象时无法访问对象成员