0

所以我有一个头文件,Graph.h。在该头文件中,我声明了一个向量。

std::vector<Vertex*> vertexList;

这个向量的元素是指向 Vertex 的指针类型,Vertex 是 Graph 的内部类。据我所知,这迫使我要么在标题中定义 Vertex 类,要么完全忘记将其作为内部类。

我真正想做的只是在 Graph.cpp 文件中定义这个 Vertex 类。我怎样才能做到这一点?

我希望我的问题很清楚。我来自 Java 世界,这样的事情更简单。

4

4 回答 4

1

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.

于 2013-04-21T01:48:47.950 回答
1

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 {
    ...
};
于 2013-04-21T01:49:47.093 回答
1

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() {...}
于 2013-04-21T01:50:49.597 回答
0

在 c++ 中,我们通常为每个类都有一个包含类接口的 .h 文件和一个包含具体实现的 c++ 文件。通常你会在 Graph.h 中包含 vertex.h。唯一会搞砸的事情是这两个 .h 文件是否相互依赖。在这种情况下,您可以只使用一行class Vertex;在 graph.h 头文件中在图形类声明之前进行转发声明。

于 2013-04-21T02:00:24.840 回答