【发布时间】:2011-06-11 17:06:22
【问题描述】:
我一次又一次地遇到这个问题,而且我总是不得不使用前向声明和指针来解决它。
C++ 需要变通方法 让对象协作似乎是错误的。有什么方法可以编译而不使 Mesh* 成为 Shape 类中的指针(或者,将 vector<Tri> 转换为 vector<Tri*>?
形状.h
#ifndef S
#define S
#include "Mesh.h"
//class Mesh ; //delete line above, uncomment this to make it work
class Shape // a mathematical shape
{
Mesh mesh ; // the poly mesh repr' this math shape
//Mesh *mesh ; // make it work
// a shape must be intersectable by a ray
//virtual Intersection intersects( const Ray& ray )=0 ;
} ;
#endif
Mesh.h
#ifndef M
#define M
#include <vector>
using namespace std;
#include "Triangle.h"
struct Mesh
{
vector<Triangle> tris ; // a mesh is a collection of triangles
} ;
#endif
三角形.h
#ifndef T
#define T
#include "Shape.h"
class Triangle : public Shape
{
// a triangle must be intersectable by a ray
// a triangle's mesh is simple but it is still a mesh (1 poly)
} ;
#endif
【问题讨论】:
-
编译器必须知道类的所有成员的大小。否则它无法为对象分配适当的空间。
-
@Bo:
sizeof(vector<Triangle>)不一定依赖于sizeof(Triangle)。 -
我不明白。您有一个形状,它拥有一个由三角形列表组成的网格,这些形状每个都拥有一个由三角形列表组成的网格?
-
@Andre:如果允许某些列表为空,则可以使用,而网格/形状似乎并非如此。
-
所以,你想要的是每个
Triangle,通过其基类的mesh数据成员,包含一个Triangle的向量。大概您希望这个向量的大小为 1,但它到底包含什么?一个三角形,它有自己的向量等。即使你用指针打破循环依赖,你也无法定义顶点的坐标。所以定义仍然是圆形的,并没有真正定义三角形。通常的解决方法是不从 Shape 继承 Triangle - 使Triangle三个点,而网格大小为 1 的Shape恰好是三角形。