简体   繁体   中英

C++ Vector of Internal Class

So I have a header file, Graph.h. Within that header file, I declare a vector.

std::vector<Vertex*> vertexList;

The elements of this vector are of type pointer to Vertex, which is a class internal to Graph. As far as I know, this forces me to either define the Vertex class in the header, or to forget about having it as an internal class altogether.

What I really want to do is only define this Vertex class inside the Graph.cpp file. How can I do this?

I hope my question is clear. I come from the Java world where things like this are more straightforward.

You can forward-declare Vertex class in the public header:

class Vertex;

That will enable usage of it's pointer anywhere.

In your implementation (private) class you can define the class body and methods:

class Vertex { ... }; 

Only parts of the code, that actually use Vertex methods, need to have access to the type definition.

If you only want to use the class as a pointer, it is enough to do this:

class Graph {

public:
    class Vertex;

};

And you can do the rest elsewhere, like this:

class Graph::Vertex {
    ...
};

If you're talking about actually having to implement all the methods of Vertex, you can do it with scoping in the .cpp file the same way you would for the Graph class: //graph.h class Graph {

  Graph();

  class Vertex {
    Vertex();
  }

 vector<Vertex*> vertexList;
};

//graph.cpp
Graph::Graph() {

//...
}

Graph::Vertex::Vertex() {
//...

}

If you want the whole definition of Vertex to only be in the .cpp file, you can use forward declaration:

//graph.h
class Vertex; //forward declaration
class Graph {

  Graph();

 vector<Vertex*> vertexList;
};

//graph.cpp
class Vertex {
  Vertex();

}

Vertex::Vertex() {...}

Graph::Graph() {...}

In c++ we generally for each class have a .h file containing the interface of the class, and a c++ file containing the concrete implementation. Typically you would include vertex.h in Graph.h. The only thing that would mess things up, is if the two .h files depend on each other. In that case you can just use one line to forward declare class Vertex; in the graph.h header file before the graph class declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM