gpt4 book ai didi

C++ - 错误 : member access into incomplete type in base class virtual function

转载 作者:行者123 更新时间:2023-11-30 03:29:32 24 4
gpt4 key购买 nike

我有一个基类Shape,它有一个虚函数intersect()

HitRecord 是在同一 .h 文件中定义的结构。

另外,Shape 有一个子类 Triangle。我试图在 Shape::intersect() 中访问 HitRecord 的成员,但出现错误 error: member access into incomplete type in base class virtual函数

奇怪的是,我可以在子类中执行此操作,但不能在基类中执行此操作。

是不是因为它是一个虚拟函数?

注意:另一个奇怪的事情:我可以在我的 Ubuntu 16.04 上运行,但在我的 mac 上遇到这个错误。

代码

struct HitRecord;   // forward declaration

class Shape {
public:
virtual bool intersect(Ray& r, HitRecord& rec) {
std::cout << "Child intersect() is not implement." << std::endl;
rec.obj = this;
return false;
}
}

struct HitRecord {
float t;
vec3f p; // point coord
vec3f norm;
Shape* obj;
};

class Triangle: public Shape {
public:
Mesh* mesh_ptr;
unsigned int vertexIndex[3];

Triangle() {...}

Triangle(Mesh* m) {...}

inline bool intersect(Ray& r, HitRecord& rec);
}

inline bool Triangle::intersect(Ray& r, HitRecord& rec) {
vec3f n = cross(v1-v0, v2-v0);
float t = - (dot(n, r.origin())+d) / dot(n, r.direction());
vec3f p = r.origin() + t*r.direction();

rec.t = t;
rec.p = p;
rec.norm = unit(n);
rec.obj = this;
return true;
}

最佳答案

这个问题被称为循环依赖。

在你的代码中..

// in shape.h

struct HitRecord; // forward declaration

// this forward declaration means all you can do until
// the struct is fully declared is declare a pointer
// or a reference to it. No more.

class Shape {
public:
virtual bool intersect(Ray& r, HitRecord& rec); // <-- this is fine


virtual bool intersect(Ray& r, HitRecord& rec) {
//...
rec.obj = this; // <-- this is where you hit an error. the compiler
// doesn't know yet what HitRecord::obj is.
return false;
}
};


.. in hitrecord.h...

struct HitRecord {
float t;
vec3f p; // point coord
vec3f norm;
Shape* obj;
};


// this would usually reside in shape.cpp, but what's important is the order
// in which the compiler reads the successive declarations

#include "shape.h"
#include "hitrecord.h" // for example...

bool Shape::intersect(Ray& r, HitRecord& rec)
{
//...
rec.obj = this; // Now, the compiler knwos all about HitRecord
// so this will compile.
return false;
}

关于C++ - 错误 : member access into incomplete type in base class virtual function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45639996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com