1.遇到的问题:教材中写着子类Graphmtx(我用GrapMatrix)继承基类Graph
但是我在子类GraphMatrix中使用父类Graph的保护成员属性:maxVertices 显示没有声明(如下图)。
原来,c++中声明一个模板类及子类,在子类中如果需要访问父类的protected变量,需要使用父类的类作用域限定符,否则会报“identifier not found”错误。如果不是模板类,可以直接访问。
例如:要如下这样使用父类的保护成员属性,太麻烦了。
所以,我就不用继承基类的方法了。直接把Graph父类的保护成员属性放到GrapMatrix类中。
2.实现程序:
(1)GraphMatrix.h
#ifndef GraphMatrix_h
#define GraphMatrix_h
#include <iostream>
using namespace std;
const int DefaultVertices = 30; // 默认最大顶点数
template <class T, class E>
class GraphMatrix {
public:
const E maxWeight = 100000; // 代表无穷大的值(=∞)
GraphMatrix(int sz=DefaultVertices); // 构造函数
~GraphMatrix(); // 析构函数
void inputGraph(); // 创建基于邻接矩阵的图
void outputGraph(); // 输出图的所有顶点和边信息
T getValue(int i); // 取顶点i的值,i不合理返回0
E getWeight(int v1, int v2); // 取边(v1, v2)上的权值
int getFirstNeighbor(int v); // 取顶点v的第一个邻接顶点
int getNextNeighbor(int v, int w); // 取v的邻接顶点w的下一个邻接顶点
bool insertVertex(const T& vertex); // 插入顶点vertice
bool insertEdge(int v1, int v2, E cost); // 插入边(v1, v2)权值为cost
bool removeVertex(int v); // 删去顶点v和所有与它相关联的边
bool removeEdge(int v1, int v2); // 在图中删去边(v1, v2)
int getVertexPos(T vertex); // 给出顶点vertice在图中的位置
private:
int maxVertices; // 图中最大的顶点数
int numEdges; // 当前边数
int numVertices; // 当前顶点数
T *VerticesList; // 顶点表
E **Edge; // 邻接矩阵
};
// 构造函数
template <class T, class E>
GraphMatrix<T, E>::GraphMatrix(int sz) {
int i, j;
maxVertices = sz;
numVertices = 0;
numEdges = 0;
VerticesList = new T[maxVertices]; // 创建顶点表数组
Edge = new E*[maxVertices]; // 创建邻接矩阵数组
for(i = 0; i < ma