std::vector for parent and child class

旧街凉风 提交于 2021-02-18 18:51:58

问题


I need to create a vector that can contain my parent class and sub class data.

This is what i do..

Vehicle is the parent class

Car is the child class

About Car.cpp , it got the following

struct Point
{
    int x,y
};

class Car : public Vehicle
{
private:
    Point wheelPoint[4];
    double area;

public:
    void setPoint();
};

void Car::setPoint()
{
    int xData,yData;

    cout << "Please enter X:";
    cin >> xData;

    cout << "Please enter Y:";
    cin >> yData;

    wheelPoint[i].x = xData;
    wheelPoint[i].y = yData;
}

Then at my main.cpp

At my main.cpp

vector<VehicleTwoD> list;
VehicleTwoD *vehicle;
Car *car = new Car;
string vehicleName;

cout << "Please input name of vehicle";
cin >> vehicleName;

vehicle = new Car;
car->setPoint();

list.push_back( Vehicle() );
list.back().setName(vehicleName);

Here the issues.. how i put my wheelPoint of car into this vector also.

What i want to achieve is a vector that can contain

Vehicle Name: Vehicle Name (private variable at Vehicle - Parent Class)
Wheel Point[0]: Point (X,Y) ( private var at Car - Child Class)
Wheel Point[1]: Point (X,Y) ( private var at Car - Child Class)
Wheel Point[2]: Point (X,Y) ( private var at Car - Child Class)
Wheel Point[3]: Point (X,Y) ( private var at Car - Child Class)

回答1:


Containers of objects suffer from object slicing. You'll need a vector of pointers (preferably smart):

vector<std::unique_ptr<Vechicle>> vehicleVector;

to which you can do:

vehicleVector.push_back(new Vehicle);
vehicleVector.push_back(new Car);

Having a vector of objects will cut off all type information that is beyond Vechicle - so, a Car will be turned into a Vehicle, losing all additional information.




回答2:


I had this same problem and I fixed it by first using and then compiling using c++14. 11 will work as well but I wanted to use some of 14's new features so I did that. I hope this helps!

#include <memory>

std::vector<std::unique_ptr<sf::Shape>> _shapes;


来源:https://stackoverflow.com/questions/13091302/stdvector-for-parent-and-child-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!