C++ 类成员函数


类的成员函数是指那些把定义和原型写在类定义内部的函数,就像类定义中的其他变量一样。类成员函数是类的一个成员,它可以操作类的任意对象,可以访问对象中的所有成员。

让我们看看之前定义的类 Box,现在我们要使用成员函数来访问类的成员,而不是直接访问这些类的成员:

  1. class Box
  2. {
  3. public:
  4. double length; // 长度
  5. double breadth; // 宽度
  6. double height; // 高度
  7. double getVolume(void);// 返回体积
  8. };

成员函数可以定义在类定义内部,或者单独使用范围解析运算符 :: 来定义。在类定义中定义的成员函数把函数声明为内联的,即便没有使用 inline 标识符。所以您可以按照如下方式定义 Volume() 函数:

  1. class Box
  2. {
  3. public:
  4. double length; // 长度
  5. double breadth; // 宽度
  6. double height; // 高度
  7. double getVolume(void)
  8. {
  9. return length * breadth * height;
  10. }
  11. };

您也可以在类的外部使用范围解析运算符 :: 定义该函数,如下所示:

  1. double Box::getVolume(void)
  2. {
  3. return length * breadth * height;
  4. }

在这里,需要强调一点,在 :: 运算符之前必须使用类名。调用成员函数是在对象上使用点运算符(.),这样它就能操作与该对象相关的数据,如下所示:

  1. Box myBox; // 创建一个对象
  2.  
  3. myBox.getVolume(); // 调用该对象的成员函数

让我们使用上面提到的概念来设置和获取类中不同的成员的值:

  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Box
  6. {
  7. public:
  8. double length; // 长度
  9. double breadth; // 宽度
  10. double height; // 高度
  11.  
  12. // 成员函数声明
  13. double getVolume(void);
  14. void setLength( double len );
  15. void setBreadth( double bre );
  16. void setHeight( double hei );
  17. };
  18.  
  19. // 成员函数定义
  20. double Box::getVolume(void)
  21. {
  22. return length * breadth * height;
  23. }
  24.  
  25. void Box::setLength( double len )
  26. {
  27. length = len;
  28. }
  29.  
  30. void Box::setBreadth( double bre )
  31. {
  32. breadth = bre;
  33. }
  34.  
  35. void Box::setHeight( double hei )
  36. {
  37. height = hei;
  38. }
  39.  
  40. // 程序的主函数
  41. int main( )
  42. {
  43. Box Box1; // 声明 Box1,类型为 Box
  44. Box Box2; // 声明 Box2,类型为 Box
  45. double volume = 0.0; // 用于存储体积
  46. // box 1 详述
  47. Box1.setLength(6.0);
  48. Box1.setBreadth(7.0);
  49. Box1.setHeight(5.0);
  50.  
  51. // box 2 详述
  52. Box2.setLength(12.0);
  53. Box2.setBreadth(13.0);
  54. Box2.setHeight(10.0);
  55.  
  56. // box 1 的体积
  57. volume = Box1.getVolume();
  58. cout << "Box1 的体积:" << volume <<endl;
  59.  
  60. // box 2 的体积
  61. volume = Box2.getVolume();
  62. cout << "Box2 的体积:" << volume <<endl;
  63. return 0;
  64. }

当上面的代码被编译和执行时,它会产生下列结果:

  1. Box1 的体积: 210
  2. Box2 的体积: 1560