Наследование классов C ++ - PullRequest
       5

Наследование классов C ++

0 голосов
/ 29 февраля 2012

У меня есть вопрос о наследовании.Из этого источника:

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

Почему мы можем использовать(*this)[id].label в графе .cpp?(*this) - это Graph объект .... если мы хотим использовать (*this)[id].label не должны ли мы объявить std::vector<Vertex>?

1 Ответ

0 голосов
/ 29 февраля 2012
class Graph: public std::vector<Vertex>

Это означает, что класс Graph унаследовал std::vector<Vertex>, поэтому вы можете делать с ним все, что вы могли бы сделать, если бы он был вектором. Итак, создав экземпляр Graph, вы фактически объявляете новый вектор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...