从Array访问对象名称

时间:2016-04-06 00:54:28

标签: c++ arrays object for-loop

使用继承类,我希望计算2d形状的面积以及3d形状的面积和体积。我现在需要访问数组确定形状,然后确定是否计算形状的面积或体积。最终目标是循环并提供输出,说明区域和/或体积的形状名称。如何访问数组的对象名称?感谢

/---------------------------------------------------------
#include <stdlib.h>
#include <cmath.h>

#include "shape.h" //header file

using namespace std;

int main() {
//Pointer Array--------------------------------------------
    Shape* arr[6];
//Assign Shape Dimensions and to Array
    Circle cir(2);  //declares value for circle ~ cir is var name
        arr[0] = &cir; //assigns cir var to array position 0
    Square sqr(3);
        arr[1] = &sqr;
    Triangle tri(4, 2);
        arr[2] = &tri;  
    Sphere sph(5);
        arr[3] = &sph;
    Cube cb(6);
        arr[4] = &cb;
    Tetrahedron trhd(7);
        arr[5] = &trhd;
//Loop each index of array and perform calculation
    for (int i = 0; i < 6; ++i)
    {
        cout << ""
    }
}

-

#topbar .ink-navigation ul.black li a.logoPlaceholder 

-

<li class="logoPlaceholder">

1 个答案:

答案 0 :(得分:0)

我建议在Shape类中添加类似toString方法的内容,并尝试在继承的类中覆盖它,如:

Class Shape{
...
public:
std::string toString();
...
}

在子类中实现并覆盖它:

std::string Shape::toString()
{
   return "This is a simple shape";
}

std::string Cube::toString()
{
   return "Cube";
}

...

通过多态的强大功能,只需调用:

即可在for循环中获取对象名称
cout << arr[i].toString() << ...