在此练习中,您将使用 C++ 可视化器和在第一个练习中创建的类图来对圆和球体类添加操作。
在上一练习中,使用了 C++ 可视化器来查看 C++ Shapes 项目的层次结构。您也可以使用 C++ 可视化器将类添加到项目,或将属性和方法添加到类。在此练习中,可将 getCircumference 方法添加到圆和球体类。 getCircumference 方法使用半径计算形状的周长和圆的圆周。
计算圆周的公式为 pi x r x r,其中 r 为圆的半径。全局常量 pi 保存在基本形状类中。
{return pi * (2 * getSize());};
<< "\n\tCircumference = " << getCircumference()
现在您已将 getCircumference 方法添加到了圆类。 getCircumference 方法使用 getSize 方法的大小变量并使用全局常量 pi 来计算圆周。您还修改了打印方法,以打印 getCircumference 方法的输出。
计算球体最大直径处圆周的公式与上一步所使用的公式相同。
{return pi * (2 * getSize());};
<< "\n\tCircumference = " << getCircumference()
现在您已使用 UML 可视化开发工具和代码编辑器将 getCircumference 方法添加到了圆和球体类。
您可以通过修改 main.cpp 类来运行该应用程序。main.cpp 类是 C++ Shapes 应用程序的驱动程序。
//instantiate and run the sphere class sphere sp; sp.print(); sp.set(); sp.print();
Shapes 程序在“控制台”视图中运行,并显示以下输出:
Enter the radius of the sphere: 10 Enter the color of the sphere: Blue Sphere: Radius = 10 Circumference = 62.8319 Area = 1256.64 Volume = 4188.79 Color = Blue
该程序显示了当前形状的大小和颜色,并提示您指定新形状的值。“控制台”视图中显示了新形状的属性。 您可以修改 main.cpp 中的代码来运行圆类。
要继续,请前进至练习 3:创建圆锥类。