gpt4 book ai didi

c++ - 尝试在另一个类中使用类时出错

转载 作者:太空狗 更新时间:2023-10-29 23:42:34 25 4
gpt4 key购买 nike

我正在用 C++ 编写一些东西。我有 2 个类,我想将它们包含在另一个类中,如下所示(这些只是头文件):

//时序.h

#ifndef _Timing_h
#define _Timing_h
#include "Agent.h"

class Timing{
private:
typedef struct Message{
Agent* _agent; //i get here a compilation problem
double _id;
} Message;
typedef struct MessageArr{
} MessageArr;
public:
Timing();
~Timing();
};
#endif

//代理.h

#ifndef _Agent_h
#define _Agent_h
#include <string>
#include "Timing.h"
using namespace std;

class Agent{
public:
Agent(string agentName);
void SetNextAgent(Agent* nextAgent);
Agent* GetNextAgent();
void SendMessage(Agent* toAgent, double id);
void RecieveMessage(double val);
~Agent();
private:
string _agentName;
double _pID;
double _mID;
Agent* _nextAgent;
};
#endif

编译错误在结构体定义里面的Timing.h文件中:

expected ';' before '*' token

我做错了什么?

最佳答案

尽量不要在 Timing.h 中包含“Agent.h”,而是包含前向引用:

#ifndef _Timing_h
#define _Timing_h
class Agent;

class Timing{
private:
typedef struct Message{
Agent* _agent; //I get here a compilation problem
double _id;
}Message;

typedef struct MessageArr{
}MessageArr;

public:
Timing();
~Timing();
};
#endif

您可以在timing.cpp 文件中包含Agent.h

这样您就可以删除循环引用并减少类之间的耦合。由于您不在类 Agent 中使用类 Timing,因此您也可以删除此包含(但这可能是您缩短的示例中的复制错误)。


基本上 - 无论何时您需要一个对象的大小或它的某些功能,您都必须包含它的头文件。如果你不需要它(例如,如果你只使用指向这个对象或引用的指针),你不应该。这减少了编译时间(尤其是对于大型项目)


对于 1 实例问题 - 查看您最喜欢的设计模式书籍(例如 GoF)。 singleton pattern 可能是您所需要的。

关于c++ - 尝试在另一个类中使用类时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3618066/

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