简体   繁体   中英

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

I'm building a little C++ game (with SFML, but that's irrelevant for the most part), and I'm changing some code around to make it more reusable. I want to make a method that shifts a bunch of shapes that are stored in an array.

Let's say we have a class called Shape , and another, its subclass, called Rectangle . I want the function to work for any shape. Is this possible? I thought I could do something like what you see below, but it crashes the game unless I change the first parameter to take an array of Rectangles.

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

Thanks for the help!

Array does not hold polimorphism, you could archive this by using vector of pointers and pass the reference to the vector into the function. Something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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