TwoDimensionalShape类应包含什么? [英] What should the TwoDimensionalShape Class contain?

查看:145
本文介绍了TwoDimensionalShape类应包含什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C ++中的多态性进行练习,以计算以下层次结构中图形的面积和体积

I am trying to do an exercise with polymorphism in C++ to calculate the area and volume of the figures int the following hierarchy

                                       Shape
                 TwoDimensionalShape            ThreeDimensional

            Circle    Square   Triangle           Sphere   Cube

我在Shape类中声明了虚函数getArea和getVolume,例如在Circle类中,该函数是:

I declared a virtual function getArea and getVolume in the Shape class, and for example in the Circle class the function is:

double Circle::getArea() const
{
    return 3.14*radius*radius;
}

其中半径在圆形类中是私有的.

where radius is private in the circle class.

但是我对在TwoDimensionalShape类中应该包含什么以及是否应该在其中声明一个可变区域一事深有感.

But I am stuck a little on what should I include in the TwoDimensionalShape class and if I should declare a variable area inside it.

推荐答案

在中间级别的类中不需要数据成员.它们只是用于层次结构抽象,以表示 Circle是TwoDimensionalShape .您以后可能会具有一些引用TwoDimensionalShape的功能,并且可以在其中传递CircleTriangle,但不能传递任何其他非TwoDimensionalShape.

You don't need a data member inside intermediate level classes. They are just for hierarchy abstraction, in order to say Circle is a TwoDimensionalShape. You may later have some function taking reference to TwoDimensionalShape and where you can pass Circle or Triangle, but not any other non-TwoDimensionalShape.

作为数据成员,您可以在Shape本身内包含一些标志.数据成员将指定当前对象的类型.您可以使用enum来表示相同的内容.这将用于静态声明和运行时检查.这也可能在某些方面有所帮助,而无需虚拟功能.

As a data-member, you can have some flag within Shape itself. The data member would specify the type of current object. You can have enum for the same. This will be used for static-asserts and well as runtime checks. This may also help in some ways without need of virtual functions.

这篇关于TwoDimensionalShape类应包含什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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