我的问题几乎在下面的代码中。我正在尝试创建一个指向抽象对象的指针数组,每个对象都有一个 ID 和成本。然后我创建像汽车和微波炉这样的对象,并分配指针指向它们。创建它们后,如何访问数组中的子数据?那可能吗。如果类是在堆中创建并指向基类数组,我什至如何访问子对象?
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;
}