我的问题主要在后面的代码中。我正在尝试创建一个指向抽象对象的指针数组,每个对象都有一个 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;
}
最佳答案
使用 protected
访问修饰符。
class Object
{
public:
virtual void outputInfo() =0;
protected:
int id;
int cost;
};
并重写 Object
的子类中的 outputInfo()
,打印 id、cost 和其他字段。
调用覆盖的方法 -outputInfo()
通过,
Object *object=new Car;
object->outputInfo();
delete object;
关于C++ 访问子类中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540861/