问题描述
我遇到这个问题的时间&再次,我一直使用一个向前的声明和指针来解决它。
I've run into this problem time & again, and I've always had to resolve it using a forward declaration and a pointer.
这似乎是错误的C ++ 需要一个工作以获得合作的对象。有没有办法让这个编译,而不使Mesh *类中的一个指针(或向量< Tri>
into vector< Tri * >
?
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*>
?
#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
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
Triangle.h
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
推荐答案
一个指针(当然,在 std :: vector
中使用指针)。你只需要仔细分析你的依赖。 Triangle
继承 Shape
,因此 Shape
的定义在上 Triangle
的。 形状
包含网格
,因此 Mesh
的定义先于形状
的。这会给出顺序:网格,形状,三角形
,它们可以毫无问题地
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.
这篇关于我在这里使用指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!