C++:如何在编译时使在同一.cpp "see"上声明的两个类?
C++: How can I make two classes declared on the same .cpp "see" each other at compile time?
在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];
};
前面的问题似乎包含了关于前向声明的很好的细节。
相关文章:
- 在声明中合并两个常量"std::set"(不是在运行时)
- C++声明双链表,使用两个 for 循环双向遍历列表并打印
- 为什么系统日志有两个不同的函数声明?
- 用相同的参数声明两个构造函数的最偶像化的方法是什么?
- 类型测试对象的动态数组的这两个声明之间的区别?
- 为什么一个接一个声明的两个变量在内存中不相邻?
- 声明一个模板函数,将模板类友元的两个对象(仅)带到这两个专用化
- 声明一个模板函数,该函数接收两个泛型迭代器作为参数
- C++地图,这两个声明如何不正确
- 错误:'x'声明中的两个或多个数据类型
- 如何在两个类之外的模板类内部的非模板类中声明的朋友函数定义
- 使用 C++11 auto 关键字声明两个(或多个)变量
- 在循环中声明两个变量以逆转字符串?在C 中
- 复制构造函数在声明两个对象时
- 如果在一行中声明两个对象,则按什么顺序构造它们
- 为什么我们不能在 for 循环中声明两个变量?
- 如何声明两个类,以便 A 具有 B 的成员,B 将 A 的成员标记为好友
- 在 for 循环中声明两个不同的变量,其中一个是不可移动、不可复制的对象
- 如何声明两个函数以彼此的签名作为参数?
- 如何在C++中声明两个相互包含(循环依赖)的类,并使用分隔符