开发者

Do I _have to_ use a pointer here?

I've run into this problem time & again, and I've always had to resolve it using a forward declaration and a pointer.

It seems wrong that C++ requires a work around to get objects to co-operate. Is there any way to get this to compile WITHOUT making Mesh* a pointer in class Shape (or, the vector<Tri> into vector<Tri*>?

Shape.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

#inc开发者_开发百科lude <vector>
using namespace std;
#include "Triangle.h"

struct Mesh
{
    vector<Triangle> tris ; // a mesh is a collection of triangles
} ;

#endif

Triangle.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


You seem basically to be saying a Shape is implemented using a Mesh and a Mesh is implemented using shapes (specifically triangles). This obviously doesn't make sense.


You cannot declare a incomplete type as an member.

When you forward declare a type, all the compiler know is that this type exists; it does not know anything about the size or members or methods. It's called an Incomplete type

Unless you include Mesh.h, Mesh is a Incomplete type and you cannot declare incomplete type as a member.

But, You can have a pointer to Incomplete type as a member and so If you forward declare class Mesh, your member will have to be Mesh*

So in conclusion, what you have said is correct.


It works for me without a pointer (there are, naturally, pointers used inside std::vector). You just have to analyze your dependencies carefully. Triangle inherits Shape, therefore Shape's definition is above Triangle's. Shape contains a Mesh, therefore Mesh's definition precedes Shape's. This gives the order: Mesh, Shape, Triangle, which compiles without errors.

Naturally, some meshes will have to have empty vectors, since every triangle inside the vector itself requires a mesh.


You've always done it right and there's no other way to do it.


You could define your mesh in terms of a different, simple, low-level triangle struct. Your high-level Triangle "shape" can share collision code with the low level one while still being a separate class. Thus Mesh.h needn't include Triangle.h. This will break your cyclic dependency and let you have a Mesh member in the Shape class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜