c++模板类相互包含



我试图创建一个模板链表代码由我自己(学习c++),但我被困在一件事。代码的简化版本如下:

LinkedList.h

#pragma once
#include "Node.h"
template<typename T>
class LinkedList
{
public:
// ...
void EditNode(Node<T> node)
{
// ... do something with the node. That's why I included "Node.h" file in the "LinkedList.h" file
}
// ...
};

Node.h

#pragma once
#include "LinkedList.h"
template<typename T>
class Node
{
public:
Node(LinkedList<T> list)
{
m_List = list;
// ... call some methods inside of list. That's why I included the "LinkedList.h" file in the "Node.h" file
}
private:
LinkedList<T> m_List;
// ...
};

我的错误是:
syntax error: identifier 'LinkedList'→这指向Node.h文件的构造函数
m_List: identifier not found->这显示在Node.h文件

中的每个m_List变量中我猜这是因为2模板类是试图包括对方,但我不确定。这里的问题是什么?

您需要在类定义之外定义函数,以便所有的类定义都在作用域中。下面是一个示例:

template<typename T> class Node;
template<typename T>
class LinkedList
{
public:
// ...
void EditNode(Node<T> node);
// ...
};
template<typename T>
class Node
{
public:
Node(LinkedList<T> list);
private:
LinkedList<T> m_List;
// ...
};
template<typename T> void
LinkedList<T>::EditNode(Node<T> node)
{
// ... do something with the node. That's why I included "Node.h" file in the "LinkedList.h" file
}
template<typename T>
Node<T>::Node(LinkedList<T> list)
{
m_List = list;
// ... call some methods inside of list. That's why I included the "LinkedList.h" file in the "Node.h" file
}

相关内容

  • 没有找到相关文章

最新更新