2012-02-29 15 views
0

私は相続に関する質問があります。このソースから:C++クラス継承

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()); 
       ... 

我々はgraph.cppで(*this)[id].labelを使用することができますなぜ? (*this)Graphオブジェクトです.... (*this)[id].labelを使用したい場合は、std::vector<Vertex>を宣言する必要はありませんか?

答えて

0
class Graph: public std::vector<Vertex> 

これは、あなたがそれがベクトルであれば、あなたが行うことができるだろうと、それを使って何を行うことができますので、グラフのクラスは、std::vector<Vertex>を継承することを意味します。そして、Graphのインスタンスを作成することで、効果的に新しいベクトルを宣言します。

+0

あなたはクラスGraphを使用することを意味します:public std :: vector は私がstd :: vector をGraphと宣言するのと同じですか? – LoveTW

+0

いいえ、Graphクラスのベクターを宣言した場合、そのクラスのメンバーになりますが、この場合Graph自体はベクターになります。 – howardh

+0

この場合、Graphはベクトルですか? – LoveTW