What should the TwoDimensionalShape Class contain?

时光怂恿深爱的人放手 提交于 2019-12-11 13:54:37

问题


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

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.

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/31074801/what-should-the-twodimensionalshape-class-contain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!