std :: vector父母和子女课

std::vector for parent and child class

本文关键字:父母 vector std      更新时间:2023-10-16

我需要创建一个可以包含我父母类和子类数据的向量。

这就是我要做的..

车辆是父级

汽车是儿童班

关于car.cpp,它有以下

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

然后在我的主角

在我的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);

这里的问题..我如何将汽车的车轮放入此矢量。

我要实现的是一个可以包含

的向量
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)

对象的容器遭受对象切片的影响。您需要指针的向量(最好是智能):

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

您可以做:

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

拥有一个对象向量将切断Vechicle之外的所有类型信息 - 因此,Car将变成Vehicle,丢失所有其他信息。

我也有同样的问题,我首先使用C 14来修复它。11也可以工作,但我想使用14个新功能中的一些,所以我做到了。我希望这会有所帮助!

#include <memory>
std::vector<std::unique_ptr<sf::Shape>> _shapes;