我的.h文件有问题

Troubles with my .h files

本文关键字:有问题 文件 我的      更新时间:2023-10-16

这是我的两个类,Node和DobleNode,它们都在不同的。h文件中,它们都有自己的。cpp文件。

//"Node.h" 
class Node
{
public:
    Node(string pName, string pID);
    void setReferencia(DobleNode *pReferencia);
    DobleNode* getReferencia(void);
private:
    string Name;
    string ID;
    DobleNode *referencia;
};
//"DobleNode.h"
class DobleNode
{
public:
    DobleNode(string pBank_code, string pCard_type);
    void setReferencia(Node *pReferencia);
    Node* getReferencia(void);
private:
    string bank_code;
    string card_type;
    Node *referencia;
};

问题是我需要一个参考。在类Node中,必须有一个DobleNode类型的属性,并且在类DobleNode中必须有一个Node类型的属性。这似乎真的很简单,我只需要在"Node.h"之前包含"DobleNode.h",一切都会工作……

但是如果我这样做了,之后,当我试图编译我的小程序时,它说标识符Node不存在。如果我用另一种方式,它说的是同样的事情,但这次标识符DobleNode是不存在的。

我如何解决这个问题,我认为一个解决方案可能是在同一个文件中有两个类,但我真的认为有一个更好的方法来解决这个问题。是否有一种方法可以"告诉"编译器同时检查"Node.h"answers"DobleNode.h",或者其他什么?

谢谢你的回答。

顺便说一句,我正在Visual Studio 2010 professional, c++(显然).

可以向前声明类,因为使用的是指针。

//"DobleNode.h"
class Node;   // DECLARED!  "Node.h" doesn't need to be included.
class DobleNode
{
    ...

//"Node.h" 
class DobleNode;   // DECLARED!  "DobleNode.h" doesn't need to be included.
class Node
{
    ...

将"class Node;"answers"class DobleNode;"放在一个/两个标头的顶部。

。(结构)

struct node1;
struct node2;
struct node1 { struct node2 *p; };
struct node2 { struct node1 *p; };

您遇到的问题是因为如果两个文件相互包含,这将导致无限循环包含。为了避免这种情况,你的代码可能有预编译头告诉它不要包含已经包含的代码。但是,这会导致一个类没有定义另一个类

有两种解决方案。你可以像Drew Dormann描述的那样向前声明。

然而,我猜你的目的使用一个虚拟类,Node和DoubleNode继承可能更合适,因为你似乎有类似的方法在每个。这将使您避免为通用方法复制代码,并使编辑更容易。

例如

//"Node.h" 
class Node : public NodeBase
{
public:
private:
    string Name;
    string ID;
};
//"DobleNode.h"
class DobleNode : public NodeBase
{
public:
private:
    string bank_code;
    string card_type;
};
//"NodeBase.h" 
class NodeBase
{
public:
    Node(string pName, string pID);
    void setReferencia(NodeBase *pReferencia);
    NodeBase* getReferencia(void);
protected:
    NodeBase *referencia;
};