C++ 如何创建从抽象类继承的动态对象数组? [英] C++ How do I create a dynamic array of objects inherited from an abstract class?

查看:37
本文介绍了C++ 如何创建从抽象类继承的动态对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的任务特别指出,我必须创建一个从抽象类 Figure 继承的正方形和三角形的随机数组,然后我必须打印出它们的正方形面积.来自 C#,我以为我会使用一组对象,但它们在 C++ 中不存在.我不允许使用诸如向量之类的东西.制作 Figure 的动态数组不起作用,因为显然它从不与抽象类一起工作.我该怎么办?请尽可能简化.

My task specifically states that I have to create a random array of Squares and Triangles, that are inherited from an abstract class Figure, and then I have to print out their square area. Coming from C#, I thought I'd be off with an array of objects, but they do not exist in C++. I'm not allowed to use anything like vectors. Making a dynamic array of Figure doesn't work because apparently it never works with abstract classes. What should I do? Please, keep it simplified if possible.

这是我当前的代码.非常基本,但它只是为了展示我正在尝试做的事情.

Here's my current code. Very basic, but it's here just to show what I'm trying to do.

#include <iostream>
#include <stdlib.h>

using namespace std;

class Figure
{
    public:
        virtual double square() = 0;
};

class Square : public Figure
{
    public:
        double side;

        double square()
        {
            return side * side;
        }
};

class Triangle : public Figure
{
    public:
        double height;
        double side;

        double square()
        {
            return 0.5 * side * height;
        }
};

void main()
{
    int size = 20;
    Figure *dyn_arr = new Figure[size]; // this doesn't work
    //Also I have to fill it somehow too...
    for (int i = 0; i < size; i++) cout << Figure.square(); //this doesn't    work either
}

推荐答案

首先 main 必须返回 int.然后,您需要创建一个指针数组,该数组将显示给抽象类 Figure.

Firstly main must return int. Then you need to create an array of pointers which will show to abstract class Figure.

Figure **dyn_arr = new Figure*[size];

然后,如果您想添加派生类的新对象,您只需像这样添加即可.

Then if you want to add a new object of the derived class you are adding simply like this.

dyn_arr[0] = new Triangle(); --> 这将创建新对象,该对象将返回该对象的地址,而您的数组实际上是指针数组.

dyn_arr[0] = new Triangle(); --> this will create new object which will return the address of that object, and your array is actually array of pointers.

最后,如果你想从任何类调用函数 square,你可以这样做.

Finnaly if you want to call the function square from any class you can do that like this.

dyn_arr[0]->square();

附言如果您对指针没有一点经验,这可能会令人困惑.

p.s. If you don't have at least a little experience with pointers this can be confusing.

这篇关于C++ 如何创建从抽象类继承的动态对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆