I have a question about inheritance. From this source:
gSpan.h
struct Edge {
int from;
int to;
int elabel;
unsigned int id;
Edge(): from(0), to(0), elabel(0), id(0) {};
};
class Vertex
{
public:
typedef std::vector<Edge>::iterator edge_iterator;
int label;
std::vector<Edge> edge;
void push (int from, int to, int elabel) //elabel代表edge label
{
edge.resize (edge.size()+1);
edge[edge.size()-1].from = from;
edge[edge.size()-1].to = to;
edge[edge.size()-1].elabel = elabel;
return;
}
};
class Graph: public std::vector<Vertex> {
public:
typedef std::vector<Vertex>::iterator vertex_iterator;
Graph (bool _directed)
{
directed = _directed;
};
bool directed;
Graph(): edge_size_(0), directed(false) {};
};
gSpan.cpp
std::istream &gSpan::read (std::istream &is)
{
Graph g(directed);
while (true) {
g.read (is);
if (g.empty()) break;
TRANS.push_back (g);
}
return is;
}
graph.cpp
std::istream &Graph::read (std::istream &is)
{
std::vector <std::string> result;
char line[1024];
while (true) {
if (result.empty()) {
// do nothing
} else if (result[0] == "t") {
...
} else if (result[0] == "v" && result.size() >= 3) {
unsigned int id = atoi (result[1].c_str());
this->resize (id + 1);
(*this)[id].label = atoi (result[2].c_str());
...
Why we can use (*this)[id].label in graph.cpp? (*this) is a Graph object…. if we want to use (*this)[id].label shouldn’t we have to declare std::vector<Vertex>?
This means that the Graph class inherited
std::vector<Vertex>, so you can do anything with it that you’d be able to do if it were a vector. And so by creating an instance of Graph, you’re effectively declaring a new vector.