5. Inheritance and class hierarchy#
点击查看考点
类的基础语法, 类层次, 虚函数调用, 资源
Implement the Shape
hierarchy designed in the picture below.
Each
TwoDimensionalShape
should contain a member functionget_area
to calculate the area of the 2D shape.Each
ThreeDimensionalShape
should have member functionsget_area
andget_volume
to calculate the surface area and volume of the 3D shape, respectively.
Create a program that uses a vector
of Shape
pointers to objects of each concrete class in the hierarchy.
The program should print the object to which each vector
element points.
If a shape is a
TwoDimensionalShape
, display its area.If a shape is a
ThreeDimensionalShape
, display its area and volume.
翻译
实现下面图片所示的 Shape
类层次.
每个
TwoDimensionalShape
应该有成员函数get_area
来计算 2D 图形的面积.每个 :cpp: ThreeDimensionalShape 应该有成员函数
get_area
和get_volume
来计算 3D 图形的表面积和体积.
编写一个程序, 它使用一个 vector
来存储 Shape
指针, 每个指针都指向类层次中的一个具体类的对象. 该程序应该打印 vector
中每个元素.
如果继承自
TwoDimensionalShape
, 输出其面积.如果继承自
ThreeDimensionalShape
, 输出其表面积和体积.
Class Hierarchy#
点击查看解答参考
警告
此卷的所有解答参考都是笔者考试时实际写的代码的回忆版, 所以 相比于其他卷的解答参考可能更为超纲难懂.
主要是在展示以 "C++98 + Lambdas + range-based for + auto + STL" 为学习内容能如何秒杀转专业题目.