2

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

这就是我所做的..

车辆是父类

汽车是儿童班

关于 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

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

2 回答 2

10

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

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

你可以这样做:

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

拥有一个对象向量将切断所有超出的类型信息Vechicle- 因此, aCar将变成 a Vehicle,丢失所有附加信息。

于 2012-10-26T17:08:51.267 回答
2

我遇到了同样的问题,我先使用然后使用 c++14 进行编译来修复它。11 也可以,但我想使用 14 的一些新功能,所以我这样做了。我希望这有帮助!

#include <memory>

std::vector<std::unique_ptr<sf::Shape>> _shapes;
于 2017-09-27T15:13:31.943 回答