C++ 访问子类中的数据

标签 c++ inheritance

我的问题主要在后面的代码中。我正在尝试创建一个指向抽象对象的指针数组,每个对象都有一个 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/

相关文章:

javascript - 将一个对象的原型(prototype)添加到另一个对象

inheritance - perl6 语法 Action 类方法似乎没有继承,命名捕获似乎没有制作

c++ - 奇怪的加法——统计一个词在一个文件中出现的次数

c++ - 在 C++ 中插入到已排序的结构数组中

python - 执行父类方法而不调用super()

ruby - 如何在 Rails 中获取子类数组

Python 类继承 : dict how to pickle(save, 加载)

c++ - 错误 : call to implicitly-deleted copy constructor of 'std::__1::unique_ptr<A, std::__1::default_delete<A>>'

c++ - 查询不断增长的数据集

c++ - 在无窗口 GLX 程序中读取 OpenGL 的默认帧缓冲区