我的.h文件有问题
Troubles with my .h files
这是我的两个类,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;
};
相关文章:
- 我似乎对if/else的基本语句有问题:/
- 我在范围内未声明的错误类有问题
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 我的C++语言蛮力算法有问题
- 我关于函数"Assert"的C++代码有问题
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- C++类中的友元函数有问题?
- 我对数组即 0x6dfe78 有问题
- 我对 std::unique(算法)C++有问题
- 使用 fstream 库并在屏幕上打印的文件有问题?
- 我的C++程序中的文件输入有问题
- 它说头文件有问题,mmsystem.h,我不能使用PlaySound()
- qt5设计器,使用fileopen,在lineedit中显示文件路径,这样做是否有问题
- 从一个目录中读取许多小文件是多么有问题
- 我的.h文件有问题
- 监控文件大小.这会有问题吗?
- 生成的 TeX 文件中存在有问题的"\\+"序列
- 同一文件上的 seekp()、seekg()、read() 和 write() 有问题
- 在头文件外部定义此函数是否有问题?(Visual Studio 2015,C++)