0

我的问题几乎在下面的代码中。我正在尝试创建一个指向抽象对象的指针数组,每个对象都有一个 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;
}
4

2 回答 2

1

使用protected访问修饰符。

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

protected:
    int id;
    int cost;
};

并覆盖打印id,成本和其他字段outputInfo()的子类。Object

调用被覆盖的方法 - outputInfo()via,

Object *object=new Car;
object->outputInfo();
delete object;
于 2012-09-22T05:04:28.500 回答
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 返回指向子类对象的指针,否则返回空指针。

于 2012-09-22T05:10:05.117 回答