繁体   English   中英

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

[英]Can you pass a subclass as an argument to a function with a superclass parameter? C++

我正在构建一个小型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);

谢谢您的帮助!

数组不保留多态性,您可以使用指针向量将其归档,然后将对向量的引用传递给函数。 就像是:

#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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM