我的问题在后面的代码中非常多。我试图创建一个指向抽象对象的数组,每个对象都有一个ID和成本。然后,我创建汽车和微波炉等物体,并指定指向它们的指针。一旦创建它们,我如何从数组中访问子数据?那可能吗。如果这些类是在堆中创建并指向基类数组的话,我甚至可以访问子对象呢?C++访问子类中的数据
class Object
{
public:
virtual void outputInfo() =0;
private:
int id;
int cost;
};
class Car: public Object
{
public:
void outputInfo(){cout << "I am a car" << endl;}
private:
int speed;
int year;
};
class Toaster: public Object
{
public:
void outputInfo(){cout << "I am a toaster" << endl;}
private:
int slots;
int power;
};
int main()
{
// Imagine I have 10 objects and don't know what they will be
Object* objects[10];
// Let's make the first object
objects[0] = new Car;
// Is it possible to access both car's cost, define in the base class and car's speed, define in the child class?
return 0;
}