两个类包含彼此的成员

Two classes contaoin members of each other

本文关键字:包含彼 成员 两个      更新时间:2023-10-16

我有两个类: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),因此它的标头保护已经被定义,阻止它的声明被处理,从而导致错误。