我必须在这里使用指针吗

Do I _have to_ use a pointer here?

本文关键字:指针 在这里      更新时间:2023-10-16

我遇到了这个问题;同样,我总是不得不使用前向声明和指针来解决它。

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

网格.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

您似乎基本上是在说Shape是使用Mesh实现的,Mesh是使用形状(特别是三角形)实现的。这显然没有道理。

不能将不完整类型声明为成员

当你正向声明一个类型时,编译器只知道这个类型存在;它对大小、成员或方法一无所知。它被称为不完整类型

除非包含Mesh.h,否则MeshIncomplete type,并且不能将不完整类型声明为成员。

但是,你可以有一个指向Incomplete type的指针作为成员,所以如果你转发声明class Mesh,你的成员必须是Mesh*

总之,你所说的是正确的。

它在没有指针的情况下对我有效(std::vector内部自然会使用指针)。你只需要仔细分析你的依赖关系。Triangle继承了Shape,因此Shape的定义高于Triangle的定义。Shape包含一个Mesh,因此Mesh的定义先于Shape的定义。这给出了顺序:Mesh, Shape, Triangle,它编译时没有错误。

自然,有些网格必须有空向量,因为向量内部的每个三角形本身都需要一个网格。

你总是做得很好,没有其他方法可以做到。

您可以用不同的、简单的、低级的三角形结构来定义网格。您的高级三角形"形状"可以与低级三角形共享冲突代码,同时仍然是一个单独的类。因此,Mesh.h不必包含Triangle.h。这将打破循环依赖关系,并让您在Shape类中拥有一个Mesh成员。