[英]Calling object method passing superclass where subclass expected
例如我有三个班级
class Shape
{
static bool collide(Box * a, Box * b)
static bool collide(Box * a, Sphere * b)
static bool collide(Sphere * a, Sphere * b)
};
class Box : public Shape{};
class Sphere : public Shape{};
例如在其他地方我有这段代码
Shape * a = new Box();
Shape * b = new Sphere();
Shape::collide(a, b);
编译器引发和错误。
如何在不添加太多逻辑的情况下自动向下转换作为参数给出的对象?
编译器无法自动转换对象,您必须手动转换它们,例如:
class Box;
class Sphere;
class Shape
{
virtual ~Shape(){}
static bool collide(Shape *a, Shape *b);
static bool collide(Box *a, Box *b);
static bool collide(Box *a, Sphere *b);
static bool collide(Sphere *a, Sphere *b);
};
class Box : public Shape{};
class Sphere : public Shape{};
bool Shape::collide(Shape *a, Shape *b)
{
if (Box *a_box = dynamic_cast<Box*>(a))
{
if (Box *b_box = dynamic_cast<Box*>(b))
return collide(a_box, b_box);
if (Sphere *b_sphere = dynamic_cast<Sphere*>(b))
return collide(a_box, b_sphere);
}
else if (Sphere *a_sphere = dynamic_cast<Sphere*>(a))
{
if (Sphere *b_sphere = dynamic_cast<Sphere*>(b))
return collide(a_sphere, b_sphere);
}
return false;
}
bool Shape::collide(Box *a, Box *b) { ... }
bool Shape::collide(Box *a, Sphere *b) { ... }
bool Shape::collide(Sphere *a, Sphere *b) { ... }
Shape * a = new Box();
Shape * b = new Sphere();
Shape::collide(a, b);
不用说,随着新形状的添加,这会变得有点乏味。 相反,您应该向Shape
本身添加一个virtual
方法,并让派生类覆盖它以根据需要处理不同的类型,例如:
class Shape
{
virtual ~Shape(){}
virtual bool collide(Shape * b) { return false; };
};
class Box : public Shape{
bool collide(Shape * b) override {
if (Box *b_box = dynamic_cast<Box*>(b)) {
return ...;
}
if (Sphere *b_sphere = dynamic_cast<Sphere*>(b)) {
return ...;
}
return Shape::collide(b);
};
};
class Sphere : public Shape{
bool collide(Shape * b) override {
if (Sphere *b_sphere = dynamic_cast<Sphere*>(b)) {
return ...;
}
return Shape::collide(b);
};
};
Shape * a = new Box();
Shape * b = new Sphere();
a->collide(b);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.