我必须在这里使用指针吗
Do I _have to_ use a pointer here?
我遇到了这个问题;同样,我总是不得不使用前向声明和指针来解决它。
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
,否则Mesh
是Incomplete 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成员。
- 努力将整数转换为链表。不知道我在这里做错了什么
- 对象指针在c++中是如何工作的
- 这个指针在c++中的用法
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 使用结构成员指针在C++中填充结构
- 当我从下面的代码中删除关键字 virtual 时,它可以正常工作,否则会出现错误。在这里"virtual"字的意义是什么?
- File.cpp.o:OpenPose 标志 CMakeFiles/.. 的多重定义/main.cpp.o:首先在这里定
- C++指针在 for 循环中被覆盖
- 为什么thread_local变量在这里从未初始化?
- 为什么我必须在这里使用dynamic_cast
- 带有 cout 的指针在C++
- 为什么我们在这里将 0 添加到双空指针上?
- 为什么两个指向相同链接的两个指针在这里表现不同
- 这个指针增量操作在这里实现了什么
- 我在这里滥用了指针吗?虽然循环条件似乎无法正常工作
- 我应该避免在这里使用指针吗?
- 链表分割错误。我猜我在这里的指针做错了什么
- 为什么在这里返回一个 malloc'd 指针会导致免费"HEAP CORRUPTION"?
- 我必须在这里使用指针吗
- 为什么指针算术不能在这里工作