C 語言使用 struct 組合資料,C++ 引入 class 將資料與操作封裝,形成「物件 = 演算法 + 資料結構」,程式由多個物件互動組成。
// C 風格 struct(不可含函式)
struct test { private: int number; public: float score; };
// C++ class(可含成員函式)
class test {
private: int number;
public:
float score;
int rp() { return number; } // 內部定義隱含 inline
void setnum(int a) { number = a; }
};
| 修飾詞 | 可存取範圍 |
|---|---|
| private | 僅本類別成員函式、友元 |
| protected | 本類別、友元、衍生類別 |
| public | 任何程式碼 |
預設值: class 預設 private;struct 預設 public。
// ballscore.h
class ballscore {
protected:
const static int GOOD = 5; // 好球加分
const static int BAD = -3; // 壞球扣分
float gradeScore; // 平均分數(受保護,外部不可直接修改)
public:
float GetGS(float good, float bad) {
gradeScore = (good * GOOD + bad * BAD) / (good + bad);
return gradeScore;
}
};
// main.cpp
#include "ballscore.h"
int main() {
ballscore jeff;
cout << jeff.GetGS(10, 3); // 僅能透過介面取得分數
// jeff.gradeScore = 5.5; // 編譯錯誤:protected 成員不可外部存取
}
inline,適合簡短函式,避免重複編譯。::,格式 回傳型別 類別名::函式名(參數)。類別內需先宣告。class test { public: void rp(); };
void test::rp() { ::globalVar = 11; this->memberVar = 100; } // :: 存取全域變數
this 指標非靜態成員函式隱含接收 this 指標,指向呼叫物件。memberVar = 100 實為 this->memberVar = 100。
成員函式支援多載(同名不同參數)。物件指標用 ->,參考用 . 呼叫成員:
void run(test* p) { cout << p->rp(100); }
void run(test& r) { cout << r.rp(200); }
類別作用域限於定義與成員函式本體。常見三種遮蔽情況:
int gradeScore 遮蔽成員 gradeScore,需用 ballscore::gradeScore 存取成員。int ballscore = 0; 遮蔽類別 ballscore,定義物件需加 class ballscore jeff;。class test { }; 遮蔽全域 int test;,存取全域需用 ::test = 1;。class test; typedef int test; 錯誤)。class 前綴區分。