< 上一课 | 下一课 >

第 2 课:扩展 circle 和 sphere 类

在本练习中,将使用 C++ 可视开发工具和第一个练习中创建的类图对 circle 和 sphere 类添加操作。

在上一个练习中,您使用了 C++ 可视开发工具来查看 C++ Shapes 项目的层次结构。还可以使用 C++ 可视开发工具对项目添加类或者对类添加属性和方法。在本练习中,将对 circle 和 sphere 类添加 getCircumference 方法。getCircumference 方法根据半径来计算形状和圆的周长。

对 circle 类添加 getCircumference 方法

圆面积的计算公式是 πr²,其中 r 是圆的半径。全局常量 π 存储在基类 shape 中。

要对 circle 类添加 getCircumference 方法:

  1. 在图编辑器中,在 classdiagram.dnx 图中右键单击 circle 类,然后单击添加 C/C++ > 方法
  2. 创建 C++ 方法窗口中,在名称字段中输入 getCircumference
  3. 返回类型列表中,选择 double,然后单击完成
  4. circle 类中,双击 getCircumference 方法,然后在代码编辑器中指定 getCircumference 的方法体,如下所示:
    {return pi * (2 * getSize());};
  5. 在代码编辑器中,在 print 方法中添加以下代码行:
    << "\n\tCircumference = " << getCircumference()
现在,已经对 circle 类添加了 getCircumference 方法。getCircumference 方法使用 getSize 方法中的 size 变量和全局常量 π 来计算周长。您还将 print 方法修改为打印 getCircumference 方法的输出。