c ++:没有强制转换的包含对象的确切类型

Sim*_*mon 3 c++ oop polymorphism inheritance covariance

我得到了经典的Shape层次结构示例......

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;
};
Run Code Online (Sandbox Code Playgroud)

一个Shapes容器,填充矩形和圆形

std::list<Shape*> container;
Run Code Online (Sandbox Code Playgroud)

和打印功能(在我的情况下,那些是碰撞检测功能)

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&) {
    ...
Run Code Online (Sandbox Code Playgroud)

当然,当我这样做时:

std::list<Shape*> it;
Rectangle r (0, 0, 32, 32);

for (it = container.begin(); it != container.end(); it++)
     print_types(r, **it);
Run Code Online (Sandbox Code Playgroud)

我不想只打印"Shape,Shape"行.我知道虚拟方法,dynamic_casts和访问者.但是,如果没有这些解决方案并保留我的外部功能,是否有任何优雅的方法可以摆脱它?

Pep*_*epe 7

您应该坚持使用虚函数并且只有一个print_types函数

void print_types(Shape&)
Run Code Online (Sandbox Code Playgroud)

然后将虚拟PrintName函数添加到基类并在派生类中重写它.

这是最优雅的方式.