我的问题几乎在随后的代码中。我正在尝试创建一个指向抽象对象的指针数组,每个对象都有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;
}
答案 0 :(得分:1)
使用protected
访问修饰符。
class Object
{
public:
virtual void outputInfo() =0;
protected:
int id;
int cost;
};
并覆盖outputInfo()
子类中的Object
,其中包含打印ID,费用和其他字段。
通过,
调用重写的方法 -outputInfo()
Object *object=new Car;
object->outputInfo();
delete object;
答案 1 :(得分: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返回指向子类对象的指针,否则返回空指针。