gpt4 book ai didi

c++ - 类的循环依赖

转载 作者:行者123 更新时间:2023-11-30 02:41:25 25 4
gpt4 key购买 nike

大家好,我有一个关于我的小项目的问题,当我尝试编译下面的代码时出现错误,我的一个类无法看到其他类,请帮助我!我认为我需要一些小修复来运行它。谢谢。

#ifndef CLIENT_H_
#define CLIENT_H_

#include <iostream>
#include <string>
#include <vector>
#include "Message.h"
#include "Server.h"


class Client
{
private:
Server* server;
string name;
vector<Message*> Messages;
public:
Client(string _name, Server* _server);
void printAllMessages();
void printUnreadedMessages();
bool sendMessage(string, string);
void reciveMessage(Message*);
string getName();
};

#endif



#ifndef SERVER_H_
#define SERVER_H_

#include "Client.h"
#include "Message.h"
#include <string>
#include <map>


class Server
{
private:
map<string,Client*> clients;
bool checkIfClientExist(string name);
public:
Server();
bool sendMessage(string,Message*);
void addClient(Client* toBeAdded);
void printAllClients();
};

#endif

在 Client.h:8:0 包含的文件中,从 Client.cpp:1: Server.h:13:13: error: ‘Client’ was not declared in this scope map clients;这是完整的错误代码

最佳答案

您的两个头文件之间存在循环依赖关系。 Client.h包含Server.hServer.h包含Client.h。在扩展 Client.h 时,它定义了它的 include guard CLIENT_H_,然后(最终)尝试扩展 Server.h,它尝试第二次包含 Client.h。 include 守卫阻止它,因为它已经被定义,所以 class Client 永远不会在 Server.h 代码被解析之前真正被定义。

这里的解决方案是如下转发声明Client:

class Client;

您可以将该行放在 Server.h 中,或者放在 Client.h 中,包含保护程序之上。

关于c++ - 类的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28156438/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com