C ++:与前向声明类和使用`#include`语句混淆

时间:2015-03-08 09:42:39

标签: c++

这是我的main.cpp

...
#include "primitive.h"
#include "intersection.h"
...

我的Primitive.h

#ifndef PRIMITIVE_H_
#define PRIMITIVE_H_

#include "intersection.h"

// Forward declaration
class Intersection;

class Primitive {
    public:
        bool intersect(Ray& ray, float* tHit, Intersection* in) {
            return false;
        }
};

class GeometricPrimitive : public Primitive {
    public:
        bool intersect(Ray& ray, float* tHit, Intersection* in) {
            DifferentialGeometry differentialGeometry;
            if (!shape->intersect(ray, tHit, &differentialGeometry)) {
                return false;
            }
            in->primitive = this;
            in->differentialGeometry = differentialGeometry;
            return true;
        }

        bool intersectP(Ray& ray) {
            return shape->intersectP(ray);
        }

        BRDFCoefficients getBRDF(DifferentialGeometry& differentialGeometry, BRDFCoefficients* brdf) {
            return material->getBRDF(differentialGeometry, brdf);
        }
};

#endif

我的Intersection.h

#ifndef INTERSECTION_H_
#define INTERSECTION_H_

// Forward declaration
class Primitive;

class Intersection {
    public:
        Primitive *primitive;

        Intersection() {

        }

        Intersection(DifferentialGeometry differntialGeometry, Primitive *primitive) {
            this->differentialGeometry = differentialGeometry;
            this->primitive = primitive;
        }
};
#endif

当我在#include "intersection.h"中遗漏Primitive.h行时,我会在行中收到错误error: member access into incomplete type 'Intersection'

in->primitive = this;in->differentialGeometry = differentialGeometry;的{​​{1}}。为什么是这样?

我是否会以通常,正确的方式宣布并使用我的Primitive.h语句(includePrimitive)?

2 个答案:

答案 0 :(得分:1)

您实际上无法使用前向声明的类型。前向声明仅告知编译器存在具有该名称的类型,但不包括其大小或其成员。因此,您无法实例化它或调用其任何成员函数。您可以做的是声明指针或对它的引用(通常是函数参数),因为所有指针都具有相同的大小。

前向声明的函数是不同的,因为你告诉编译器不是他们的名字,坚果也是他们的签名,这足以让编译器创建调用端代码(例如准备参数,为返回值分配空间并跳转到符号,链接器稍后将转换为实际地址

答案 1 :(得分:0)

也许你只是忘了把

#ifndef Intersection_H
#define Intersection_H

如果没有这个条件,你将包括intersection.h两次并导致错误。 看看这篇文章: http://en.wikipedia.org/wiki/Include_guard