class 關鍵字定義類,成員分為數據成員(屬性)與成員函數(方法),通過訪問標簽控制可見性。
class ClassName {
// private: 默認(類內可見,外部不可見)
int privateVar;
protected:
// protected: 類內 + 派生類可見
int protectedVar;
public:
// public: 任何可見類的地方均可見
void publicFunc();
int publicVar;
} objectName; // 可選:直接定義對象
| 關鍵字 | 類內 | 派生類 | 外部代碼 |
|---|---|---|---|
| private | ✓ | ✗ | ✗ |
| protected | ✓ | ✓ | ✗ |
| public | ✓ | ✓ | ✓ |
class CRectangle {
int width, height; // private 默認
public:
void set_values(int w, int h); // 聲明
int area() const { return width * height; } // 內聯定義
};
// 類外定義需作用域解析符 ::
void CRectangle::set_values(int w, int h) {
width = w; height = h;
}
int main() {
CRectangle rect;
rect.set_values(3,4);
cout << "Area: " << rect.area() << endl; // 12
// rect.width = 5; // 錯誤:private 不可訪問
}
void 也無)class CRectangle {
int width, height;
public:
CRectangle(int w, int h) : width(w), height(h) {} // 成員初始化列表(推薦)
CRectangle() : width(5), height(5) {} // 默認構造
int area() const { return width * height; }
};
CRectangle r1(3,4); // 調用帶參構造
CRectangle r2; // 調用默認構造
// CRectangle r3(); // ❌ 最令人糾結的解析:聲明函數!
~ClassName(),無參、無返回delete)delete 動態內存、關閉文件/句柄、解鎖class CRectangle {
int *width, *height; // 動態分配演示
public:
CRectangle(int w, int h) {
width = new int(w);
height = new int(h);
}
~CRectangle() { // 析構釋放
delete width;
delete height;
}
int area() const { return *width * *height; }
};
CRectangle obj;
CRectangle* ptr = &obj;
CRectangle* arr = new CRectangle[3]; // 動態數組
// 訪問成員
obj.area(); // 對象用 .
ptr->area(); // 指針用 ->
arr[0].area(); // 數組元素用 .
(arr+1)->area(); // 指針算術等價
// 釋放動態數組
delete[] arr; // 必須用 delete[]
| 關鍵字 | 默認訪問 | 默認繼承 | 特殊語義 |
|---|---|---|---|
| class | private | private | 標準類 |
| struct | public | public | C 兼容,可含成員函數 |
| union | public | public | 共享內存,同一時刻僅一成員有效,C++11 允許非平凡類型 |
struct Point { int x, y; }; // 全 public,適合純數據聚合
union Variant { int i; float f; char c; }; // 共用 4 字節
getter/setter)控制訪問const/引用成員必須)T(const T&)、T& operator=(const T&)if (this != &rhs) { ... }const 對象只能調用 const 成員函數new/delete 和裸數組類是 C++ 面向對象的核心,封裝實現不變式、管理資源生命周期、支持多態。掌握訪問控制、構造/析構/拷貝語義、初始化列表、RAII 與 Rule of Three/Five/Zero,是編寫健壯、可維護 C++ 代碼的基石。