C++:如何在编译时使在同一.cpp "see"上声明的两个类?

C++: How can I make two classes declared on the same .cpp "see" each other at compile time?

本文关键字:声明 两个 see 编译 C++ cpp      更新时间:2023-10-16

在VS2008上编译此代码时:

  #include <vector>
using namespace std;
class Vertex {
public: double X; 
        double Y;
        double Z;
        int id; // place of vertex in original mesh vertex list
        vector<Vertex*> neighbor; //adjacent vertices
        vector<Triangle*> face; // adjacent triangles
        float cost; // saved cost of collapsing edge
        Vertex *collapse; // 
};

 class Triangle {
public:
    Vertex * vertex[3]; 

};

我得到以下错误:

1>.Triangle.cpp(15) : error C2065: 'Triangle' : undeclared identifier 

我该如何解决这个问题?

使用前向声明:

class Traingle;
class Vertex
{
    ...
};
class Triangle
{
    ...
};

类型的前向声明(例如class Triangle)允许声明指向该类型的指针或引用,但不能声明该类型的对象。换句话说

class Triangle;
class Vertex
{
  vector<Triangle*> face;
};

可以编译,但是

class Triangle;
class Vertex
{
  vector<Triangle> face;
};

将无法编译。

同样,类型的前向声明不允许访问它的成员,因为编译器还不知道它们。因此,使用前向声明类型的对象的成员函数必须在类型完全定义之后才定义。在您的例子中,在class Triangle的定义之后。

哦,这并不是Visual Studio所特有的。

需要在Vertex类之前声明Triangle类。在本例中,它看起来像这样:

#include <vector>
using namespace std;
class Triangle;
class Vertex {
public:
        double X; 
        double Y;
        double Z;
        int id; // place of vertex in original mesh vertex list
        vector<Vertex*> neighbor; //adjacent vertices
        vector<Triangle*> face; // adjacent triangles
        float cost; // saved cost of collapsing edge
        Vertex *collapse; // 
};
class Triangle {
public:
    Vertex * vertex[3]; 
};

前面的问题似乎包含了关于前向声明的很好的细节。