C++:如何使在同一个 .cpp 上声明的两个类“看到”编译时彼此?
在 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
如何解决此问题?
When compiling this code on 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];
};
I get the following error:
1>.\Triangle.cpp(15) : error C2065: 'Triangle' : undeclared identifier
How can I fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用前向声明:
类型的前向声明(例如
class Triangle
)允许您声明该类型的指针或引用,但不能声明该类型的对象。换句话说,会编译,但
不会编译。
此外,类型的前向声明不允许您访问其成员,因为编译器还不知道它们。因此,使用前向声明类型的对象的成员函数必须在类型完全定义之后定义。在您的情况下,在
class Triangle
的定义之后。哦,这根本不是 Visual Studio 特有的。这只是标准的 C++。
You use a forward declaration:
A forward declaration of a type (e. g.
class Triangle
) allows you to declare pointers or references to that type, but not objects of the type. In other wordswill compile, but
will not compile.
Also, a forward declaration of a type does not let you access its members, because the compiler does not know about them yet. So the member functions that use objects of the forward declared type must be defined after the type is fully defined. In your case, after the definition of
class Triangle
.Oh, and this is not at all specific to Visual Studio. This is just standard C++.
您需要在 Vertex 类之前转发声明 Triangle 类。在这种情况下,看起来像这样:
这个上一个问题似乎包含很好的细节关于前向声明。
You need to forward declare the Triangle class before the Vertex class. In this case that would look something like this:
This previous question seems to contain good details about forward declaration.