C++ 類成員函式



類的成員函式是指其定義或原型在類定義中像任何其他變數一樣。它對屬於其成員的類的任何物件進行操作,並且可以訪問該物件類的所有成員。

讓我們以之前定義的類為例,使用成員函式訪問類的成員,而不是直接訪問它們:

class Box {
   public:
      double length;         // Length of a box
      double breadth;        // Breadth of a box
      double height;         // Height of a box
      double getVolume(void);// Returns box volume
};

定義類成員函式

成員函式可以在類定義中定義,也可以使用作用域解析運算子 :單獨定義。在類定義中定義成員函式會宣告該函式為內聯函式,即使您沒有使用內聯說明符。因此,您可以將Volume()函式定義如下:

在類內定義成員函式

class Box {
   public:
      double length;      // Length of a box
      double breadth;     // Breadth of a box
      double height;      // Height of a box
   
      double getVolume(void) {
         return length * breadth * height;
      }
};

在類外定義成員函式

如果您願意,可以使用作用域解析運算子 (::)在類外定義相同的函式,如下所示:

double Box::getVolume(void) {
   return length * breadth * height;
}

這裡,唯一需要注意的是,您必須在 :: 運算子之前使用類名。

呼叫(訪問)成員函式

成員函式將使用點運算子 (.)在物件上呼叫,它只操作與該物件相關的資料,如下所示:

Box myBox;          // Create an object

myBox.getVolume();  // Call member function for the object

示例

讓我們將上述概念應用於設定和獲取類中不同類成員的值:

#include <iostream>

using namespace std;

class Box {
   public:
      double length;         // Length of a box
      double breadth;        // Breadth of a box
      double height;         // Height of a box

      // Member functions declaration
      double getVolume(void);
      void setLength( double len );
      void setBreadth( double bre );
      void setHeight( double hei );
};

// Member functions definitions
double Box::getVolume(void) {
   return length * breadth * height;
}

void Box::setLength( double len ) {
   length = len;
}
void Box::setBreadth( double bre ) {
   breadth = bre;
}
void Box::setHeight( double hei ) {
   height = hei;
}

// Main function for the program
int main() {
   Box Box1;                // Declare Box1 of type Box
   Box Box2;                // Declare Box2 of type Box
   double volume = 0.0;     // Store the volume of a box here
 
   // box 1 specification
   Box1.setLength(6.0); 
   Box1.setBreadth(7.0); 
   Box1.setHeight(5.0);

   // box 2 specification
   Box2.setLength(12.0); 
   Box2.setBreadth(13.0); 
   Box2.setHeight(10.0);

   // volume of box 1
   volume = Box1.getVolume();
   cout << "Volume of Box1 : " << volume <<endl;

   // volume of box 2
   volume = Box2.getVolume();
   cout << "Volume of Box2 : " << volume <<endl;
   return 0;
}

當以上程式碼編譯並執行時,會產生以下結果:

Volume of Box1 : 210
Volume of Box2 : 1560
廣告