您可以将子类作为参数传递给具有超类参数的函数吗? C ++

时间:2013-06-16 21:45:24

标签: c++ function inheritance

我正在构建一个小小的C ++游戏(使用SFML,但这与大多数情况无关),而且我正在改变一些代码以使其更具可重用性。我想创建一个方法来移动存储在数组中的一堆形状。

假设我们有一个名为 Shape 的类,另一个是它的子类,名为 Rectangle 。我希望该函数适用于任何形状。这可能吗?我以为我可以做类似你在下面看到的内容,但除非我更改第一个参数以获取一个矩形数组,否则它会崩溃。

void shift_shapes(Shape *shapes, int num_shapes, int x_offset, int y_offset)
{
    for (int i = 0; i < num_shapes; i++)
        shapes[i].move(x_offset, y_offset);
}

Rectangle rects[100];
// *Add 100 rectangles*
shift_shapes(rects, 100, 10, 5);

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

Array不支持多态,你可以通过使用指针向量并将向量的引用传递给函数来实现。类似的东西:

#include <memory>
#include <vector>

void shift_shapes(std::vector<std::unique_ptr<Shape> >& shapes, int num_shapes, int x_offset, int y_offset)
{
    for (int i = 0; i < num_shapes; i++)
    {
        shapes[i].move(x_offset, y_offset);
    }
}
相关问题