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

标签 c++ forward-declaration

在 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 的。这只是标准的 C++。

关于C++:如何在编译时使两个类在同一个 .cpp "see"上声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8099051/

相关文章:

C++ 对象的前向声明

c++ - 针对 pimpl 的最终用户,pimpl 中的全局和私有(private)前向声明之间的区别

Android studio 3 c++ 文件充满错误但编译正常

c++ - 如何将字符保存到字符数组中

c++ - 我很难将我的一些代码从 main 移动到函数

C++前向声明和不完整类型

C: 前向声明一个 typedef,稍后定义用于现在声明一个函数

c++ - 前向声明和命名空间 (c++)

c++ - 如何在windows上获取cpu上的实际内核数?

c++ - 如何测量队列中每秒弹出/推送的速率?