2012-09-22 18 views
0

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

回答

1

使用protected訪問修飾符。

class Object 
{ 
public: 
    virtual void outputInfo() =0; 

protected: 
    int id; 
    int cost; 
}; 
Object子類,其打印ID,成本等各個領域

,並覆蓋outputInfo()

調用覆蓋的方法 - 通過outputInfo()

Object *object=new Car; 
object->outputInfo(); 
delete object; 
0

您需要使用dynamic_cast的向下轉型到子類:

if (Car* car = dynamic_cast<Car*>(objects[0])) 
{ 
    // do what you want with the Car object 
} 
else if (Toaster* toaster = dynamic_cast<Toaster*>(objects[0])) 
{ 
    // do what you want with the Toaster object 
} 

的dynamic_cast返回一個指向子類對象,如果對象的運行時類型實際上是那個子類,否則就是一個空指針。