2012-09-22 17 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返回一个指向子类对象,如果对象的运行时类型实际上是那个子类,否则就是一个空指针。