我得到了经典形状层次结构示例...C++:没有包含的对象的确切类型转换
struct Shape { // abstract type
Shape (int x, int y);
int x;
int y;
};
struct Rectangle : public Shape {
Rectangle (int x, int y, int w, int h);
int w;
int h;
};
struct Circle : public Shape {
Circle (int x, int y, int r);
int r;
};
一个形状的容器中,填充有矩形和圆形
std::list<Shape*> container;
和打印功能(在我的情况下,这些是碰撞检测功能)
void print_types (Shape&, Shape&) {
std::cout << "Shape, Shape" << std::endl;
}
void print_types (Rectangle&, Rectangle&) {
std::cout << "Rectangle, Rectangle" << std::endl;
}
void print_types (Rectangle&, Circle&) {
...
当然,当我这样做时:
std::list<Shape*> it;
Rectangle r (0, 0, 32, 32);
for (it = container.begin(); it != container.end(); it++)
print_types(r, **it);
我不想只打印“形状,形状”线。我知道虚拟方法,dynamic_casts和访问者。但是如果没有这些解决方案并保留我的外部功能,是否有任何优雅的方式可以摆脱它?
优雅的方法是使用它设计的语言。这意味着“虚拟方法,dynamic_casts和访客”。 – 2011-05-03 21:12:59
@Mark:理想情况下不是dynamic_casts,尽管... – 2011-05-03 21:18:11
@Oli,该语言的每个功能都是有原因的。我曾经找到一个dynamic_cast的例子,如果你不同意,你可以在那里留下一个注释:http://Marketing.com/questions/28080/how-bad-is-dynamic-casting/303312#303312 – 2011-05-03 21:21:38