c – 一个继承自两个类的类,具有相同的函数原型,相互冲突
我正在处理Ray Tracing任务,这是有问题的来源:
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 } }; 上面的源代码无法编译,错误信息: error: conflicting return type specified for ‘virtual bool BoundingSphere::intersectionTest(const Ray&)’ error: overriding ‘virtual RayTask Sphere::intersectionTest(const Ray&) 我想在Sphere中使用方法实现BoundingSphere :: intersectionTest,所以我需要继承BoundingVolume和Sphere.但是由于继承了具有不同返回类型的相同参数列表的函数,所以搞砸了…… 我不想重复具有相同功能的代码…… 解决方法
编译器试图覆盖具有不同返回类型的两个虚拟方法,这是不允许的:如果编译器不知道返回类型将是什么,它将如何知道为函数调用分配多少内存?这两种方法不能有相同的名称;尝试将一个更改为更合适的含义.
如果你觉得这些名字最能代表他们所提供的行动的意义(我不确定),我还建议你仔细考虑你的等级制度.球形BoundingVolume真的是一个球体吗?也许不是:它是用Sphere(私有继承,不解决你的问题)实现的,或者它有一个Sphere(组合,在这个简单的情况下可以解决你的问题).但是,后一种情况可能会给移动复杂类带来问题,你希望BoundingSphere拥有Sphere的所有方法.或者,您是否需要区分BoundingVolumes和普通Geometrys? 该问题的另一个解决方案是对这些层次结构中的一个使用非成员函数,使用Koenig查找(参数的类型)调用正确的版本.我不能不知道你的等级制度是什么样子.但要考虑你的设计:如果你有相同命名的操作给你完全不同的语义结果,那么操作是否正确命名/设计? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |