gpt4 book ai didi

c++ - 将基类的对象传递给派生类的引用函数

转载 作者:行者123 更新时间:2023-12-03 06:57:47 26 4
gpt4 key购买 nike

我正在尝试编写代码,以找到许多不同类型的形状之间的距离。我已经使用Shape函数定义了一个基类virtual distance(Shape& otherShape)来查找与另一个形状的距离,然后想为所有派生类定义该距离。
问题是有很多可能的形状对,所以我的解决方案是在类之外定义一组距离函数(圆-圆,圆-正方形,正方形-tri等),然后从距离功能。我在下面添加了一个微型示例,仅用一个派生类Circle演示了此问题。
当我尝试调用特定的circleCircleDistance函数时,出现错误,因为它无法将基类转换为派生类。有什么办法可以解决这个问题,还是我的设计无法正常工作?

enum ShapeType{CIRCLE, SQUARE};

class Shape {
public:
ShapeType type;
virtual double distance(Shape& otherShape) = 0;
};

class Circle : public Shape {
public:
ShapeType type = CIRCLE;
double distance(Shape& otherShape) override;
};


double circleCircleDistance(Circle& circle1, Circle& cirlce2){
return 0; //pretend this does the calculation
};

double Circle::distance(Shape &otherShape) {
switch (otherShape.type){
case CIRCLE:
//Here I get the error
//cannot bind base class object of type Shape to derived class reference Circle& for 2nd argument
return circleCircleDistance(*this, otherShape);

}
}

最佳答案

您将必须将Shape&转换为Circle&

return circleCircleDistance(*this, static_cast<Circle&>(otherShape));
顺便说一句,我会以不同的方式处理您的类型
class Shape {
public:
virtual ShapeType get_type() const = 0; // derived classes must override this
virtual double distance(Shape& otherShape) = 0;
};

class Circle : public Shape {
public:
ShapeType get_type() const override { return CIRCLE; } // here's your override
double distance(Shape& otherShape) override;
};

...
{
switch (otherShape.get_type()){
否则,您将陷入一种情况,即 type被派生类/基类遮盖了,具体取决于您访问它的方式。

关于c++ - 将基类的对象传递给派生类的引用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64266025/

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