在此练习中,您可通过使用可视化编辑器来创建圆锥类。 圆锥类表示 3 维圆锥。
在上一练习中,您使用了 UML 建模工具来扩展圆和球体类。在此练习中,您将使用 UML 建模工具将圆锥类添加到项目中。继承自 shape3d 类的圆锥类根据圆锥的半径和高度来计算和显示体积和面积。 您可以使用 UML 建模工具将类添加到项目并将属性添加到类。 要编辑方法的主体,请双击图中的方法,并在代码编辑器中编辑源代码。
您可以使用 C/C++ Project Explorer 视图将类添加到项目。通过使用新建 C++/类向导,您可以确定所有继承关系。
现在您已将圆锥类添加到 Shapes 项目中。您可以使用 UML 建模工具来添加类并将属性添加到新类。 您的图看上去应该与下图相似:
圆锥类实施基本形状类定义的 getColor 和 setColor 方法。
现在您已将 getColor 和 setColor 方法添加到圆锥类。
圆锥类实施基本形状类定义的 getSize 和 setSize 方法。 大小字段存储了圆锥的高度。
您已将 getSize 和 setSize 方法添加到圆锥类。
圆锥类实施基本形状类定义的 getRadius 和 setRadius 方法。 半径字段存储圆锥底面的半径。 应用程序使用半径来计算圆锥的圆周和体积。
现在您已将 getRadius 和 setRadius 方法添加到圆锥类。
圆锥类实施 shapes3d 类定义的计算面积和体积的方法。计算圆锥面积的公式为 pi * r * (r + (r2 + h2)1/2)。 计算圆锥的体积的公式为 1/3 x pi x r2 h。
现在您已将 surfaceArea 和 volume 方法添加到圆锥类。
圆锥类实施基本形状类定义的 set 和 print 方法。
{ cout << "Cone:" << "\n\tLength = " << getSize() << "\n\tArea = " << surfaceArea() << "\n\tVolume = " << volume() << "\n\tColor = " << getColor() << "\n\n"; };
现在您已将 print 和 set 方法添加到圆锥类。
cone.cpp 类文件包含 set 方法、构造函数和析构函数的实施。 您要修改 set 方法的主体以提示用户输入圆锥的大小和半径。 同时您还必须编辑缺省构造函数来设置新圆锥类的初始值。
void cone::set() { double size; double radius; string color; cout << "Enter the height of the cone: "; cin >> size; setSize(size); cout << "Enter the radius of the base of the cone: "; cin >> radius; setRadius(radius); cout << "Enter the color of the cone: "; cin >> color; setColor(color); }
现在,通过将 set 方法添加到 cone.cpp 类文件,您已完成了 Shapes 项目。
在运行应用程序之前,必须将 include 语句添加到 main.cpp 类来包括新的圆锥类。您可以通过修改 main.cpp 类来运行应用程序并实例化新的圆锥类。
//instantiate and run the cone class cone c; c.print(); c.set(); c.print();
程序显示了圆锥的大小、颜色、面积和体积,并提示您指定新圆锥实例的值。