unfortunately, I can't use std::vector
and have to use plain C++ arrays. I got the following code:
class Base
{
}
class DerivedCar : Base
{
public:
DerivedCar(int a) a(a) {};
private:
int a;
}
class DerivedHouse : Base
{
public:
DerivedHouse(float b) b(b) {};
private:
float b;
}
class Vector
{
Vector() :
index(0)
void add(const DerivedCar& car)
{
vec[index] = new DerivedCar(car.a);
index++;
}
void add(const DerivedHouse& house)
{
vec[index] = new DerivedHouse(house.b);
index++;
}
private:
Vector vec[100];
int index;
}
int main()
{
Vector vector;
DerivedCar car(100);
DerivedHouse house(2.f);
vector.add(car);
vector.add(house);
}
I would like to have an array of type Base
and add objects of a derived type.
Is there a better approach to this other than the way I did? What would be the best way to keep copying of objects at a minimum.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…