- C++ 基礎
- C++ 首頁
- C++ 概述
- C++ 環境設定
- C++ 基本語法
- C++ 註釋
- C++ Hello World
- C++ 省略名稱空間
- C++ 常量/字面量
- C++ 關鍵字
- C++ 識別符號
- C++ 資料型別
- C++ 數值資料型別
- C++ 字元資料型別
- C++ 布林資料型別
- C++ 變數型別
- C++ 變數作用域
- C++ 多個變數
- C++ 基本輸入/輸出
- C++ 修飾符型別
- C++ 儲存類
- C++ 運算子
- C++ 數字
- C++ 列舉
- C++ 引用
- C++ 日期和時間
- C++ 控制語句
- C++ 決策制定
- C++ if 語句
- C++ if else 語句
- C++ 巢狀 if 語句
- C++ switch 語句
- C++ 巢狀 switch 語句
- C++ 迴圈型別
- C++ while 迴圈
- C++ for 迴圈
- C++ do while 迴圈
- C++ foreach 迴圈
- C++ 巢狀迴圈
- C++ break 語句
- C++ continue 語句
- C++ goto 語句
- C++ 建構函式
- C++ 建構函式和解構函式
- C++ 複製建構函式
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
廣告