父类和子类的 std::vector [英] std::vector for parent and child class

查看:63
本文介绍了父类和子类的 std::vector的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这就是我所做的..

Vehicle 是父类

汽车是子类

关于 Car.cpp ,它有以下内容

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

然后在我的 main.cpp

Then at my main.cpp

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

推荐答案

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

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

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

你可以这样做:

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

拥有对象向量将切断Vechicle之外的所有类型信息 - 因此,Car 将变成Vehicle, 丢失所有附加信息.

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.

这篇关于父类和子类的 std::vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆