4

I am working on a Ray Tracing task, here is the problematic source:

class Geometry
{
    public:
        virtual RayTask *intersectionTest(const Ray &ray) = 0;
};

class Sphere : public Geometry
{
    public:
        RayTask *intersectionTest(const Ray &ray);
};

class BoundingVolume
{
    public:
        virtual bool intersectionTest(const Ray &ray) = 0;
};

class BoundingSphere : public Sphere, BoundingVolume
{
    public:
        bool intersectionTest(const Ray &ray) // I want this to be inherited from BoundingVolume
        {
            return Sphere::intersectionTest(ray) != NULL; // use method in Sphere
        }
};

source above can not compile, error information:

error: conflicting return type specified for ‘virtual bool BoundingSphere::intersectionTest(const Ray&)’
error:   overriding ‘virtual RayTask Sphere::intersectionTest(const Ray&)

I want to implement BoundingSphere::intersectionTest using method in Sphere, so I need to inherit from both BoundingVolume and Sphere. but due to inherit functions that has the same parameter list with different return type, things messed up...

I do not want to duplicate codes with the same functionality... could any one give me a solution?...

4

1 回答 1

1

编译器试图覆盖两个具有不同返回类型的虚方法,这是不允许的:如果编译器不知道返回类型是什么,它如何知道为函数调用分配多少内存?这两个方法不能有相同的名称;尝试将一个更改为更合适的含义。

如果您认为这些名称最能代表它们都提供的操作的含义(我不确定),我还建议您仔细考虑您的层次结构。球体BoundingVolume真的是一个Sphere吗?也许不是:它是根据Sphere(私有继承,不能解决你的问题)实现的,或者它有一个Sphere(组合,在这个简单的情况下会解决你的问题)。但是,后一种情况可能会给移动复杂类带来问题,因为您希望 aBoundingSphere拥有Sphere. 或者,也许,您需要区分sBoundingVolumes和 normal Geometrys 吗?

该问题的另一种解决方案是对这些层次结构中的一个使用非成员函数,并使用 Koenig 查找(参数的类型)调用正确的版本。我不能说不知道你的层次结构是什么样的。但是请考虑您的设计:如果您有同名操作给您返回完全不同的语义结果,那么该操作是否正确命名/设计?

于 2012-04-29T18:42:18.657 回答