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);
E getWeight(int v1, int v2);
int getFirstNeighbor(int v);
int getNextNeighbor(int v, int w);
bool insertVertex(const T& vertex);
bool insertEdge(int v1, int v2, E cost);
bool removeVertex(int v);
bool removeEdge(int v1, int v2);
int getVertexPos(T vertex);
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