用C++实现一个图类
Implementing a graph class in C++
这是我的类:
template <class T>
class Vertex
{
private:
T data;
Vertex<T>* next;
public:
friend class Graph;
Vertex(T dat, Vertex<T>* nex)
{
data=dat; next = nex;
}
};
template <class T>
class Graph
{
public:
Vertex<T>* head;
Graph() : head(NULL)
{
}
void insert(T data)
{
Vertex<T>* ptr = new Vertex<T>(data, head);
head = ptr;
}
};
和主要:
int main()
{
Graph<int> graph;
graph.insert(1);
}
当我编译它时,告诉我:
graph.h: In instantiation of ‘Vertex<int>’:
graph.h:30: instantiated from ‘void Graph<T>::insert(T) [with T = int]’
main.cpp:6: instantiated from here
graph.h:10: error: template argument required for ‘struct Graph’
是什么导致了这个问题?
在友元语句中使用Graph
类时,必须"前向声明":
template <class T>
class Graph;
template <class T>
class Vertex
{
private:
//...
public:
friend class Graph<T>;
// ... and so on
正如错误消息所说,无论在哪里使用Graph类,都需要为它提供模板参数
friend class Graph<T>;
代替
friend class Graph;
实际上,不需要正向声明。如果类或函数尚未定义,则友元声明将创建正向声明。标准明确说明了这一点。你应该写:
template <class T> friend class Graph;
这将有效地将Graph
的所有实例化声明为当前类的朋友。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '