我的問題在後面的代碼中非常多。我試圖創建一個指向抽象對象的數組,每個對象都有一個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;
}