尝试实现邻接矩阵图并练习OOP。我一直坚持执行inserNode(string)方法。
我的麻烦在于访问私有数据字段。我完全想念什么?
某些错误:
Graph.cpp:30:26:错误:未知类型名称'node' graph [id] =新节点; ^
Graph.cpp:35:10:错误:使用未声明的标识符'numnodes' numnodes ++;
Graph.cpp:34:19:错误:预期为';'声明结束时 graph [id]-> nodename = name;
Graph.cpp:34:15:错误:分解声明'[id]'需要初始化程序
graph.h
#include <iostream>
using namespace std;
class Graph {
public:
Graph();
int insertNode(string name);
private:
static const int vertices = 20;
int nodeCount;
struct node {
int nodeid; // node position in graph[]
string nodename; // username
};
// pointers to the graph nodes
node *graph[vertices];
// adjacency matrix for graph. True if edge is going from node i to j.
bool edges[vertices][vertices];
};
#endif
graph.cpp
#include "Graph.h"
Graph::Graph() {
for (int i = 0; i < vertices; i++) {
graph[i] = 0;
for (int j = 0; j < vertices; j++ )
edges[i][j] = 0;
}
}
/* create node and insert pointer in first available graph position. Returns id value, -1 if unsuccessful. */
int insertNode(string name) {
int id = 0;
while (id < vertices) {
if (graph[id] == NULL) {
graph[id] = new node;
if (!graph[id])
return -1;
graph[id]->nodeid = id;
graph[id]->nodename = name;
numnodes++;
return id;
}
id++;
}
return -1;
}
答案 0 :(得分:1)
您定义的insertNode
与您在Graph
中声明的方式不同。您刚刚制作了一个名为insertNode
的免费函数,该函数不是Graph
的成员,因此无法访问Graph
。您需要这样定义它:
int Graph::insertNode(string name)
{
}