std :: vector父母和子女课
std::vector for parent and child class
我需要创建一个可以包含我父母类和子类数据的向量。
这就是我要做的..
车辆是父级
汽车是儿童班
关于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;
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 在c++中用vector填充一个简单的动态数组
- vector.resize()中的分配错误
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 在某些循环内使用vector.push_back时出现分段错误
- 当vector是tje全局变量时,c++中vector的内存管理
- std::vector的包装器,使数组的结构看起来像结构的数组
- 为什么(-1)%vector::size()总是返回0
- 在C++中将类(带有Vector成员)保存为二进制文件
- 编译器如何区分std::vector的构造函数
- 将 int 数组转换为 std::vector<int*>
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 在std::vector上存储带有模板的类实例
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么std::vector比数组慢
- std::vector::迭代器是否可以合法地作为指针
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 循环中的条件:为什么每次都调用strlen(),而vector.size()只调用一次
- std :: vector父母和子女课