class ClassName {
private: // 私有成員:僅類內部可存取
// 資料成員、成員函數
protected: // 保護成員:類內部及衍生類可存取
// 資料成員、成員函數
public: // 公有成員:任何地方可存取(介面)
// 資料成員、成員函數
}; // 分號不可省略
class 關鍵字定義類。Student)。private。private:封裝內部實作細節。public:提供外部介面(多為成員函數)。protected:支援繼承體系的擴充。class Point {
int x, y;
public:
void Set(int a, int b) { x = a; y = b; } // 適合簡短函數
};
// 類內宣告
class Point {
int x, y;
public:
void Set(int a, int b);
};
// 類外實作
void Point::Set(int a, int b) { // 作用域解析運算子 ::
x = a; y = b;
}
// 物件宣告
ClassName obj1, obj2, obj3; // 多個物件用逗號分隔
// 物件指標
ClassName* pObj = &obj1; // 指向現有物件
ClassName* pNew = new ClassName(); // 動態配置,需 delete
obj.MemberFunc()、obj.dataMember(若 public)。pObj->MemberFunc()、pObj->dataMember。將資料成員設為 private,提供 public 的 getter/setter 方法,可在存取時加入驗證、日誌、延遲初始化等邏輯,實現資料隱藏與介面穩定。
class Student {
int id; // 私有
char name[32]; // 私有
public:
Student(int i, const char* n) : id(i) { strcpy(name, n); }
void Print() const { printf("ID:%d Name:%s\n", id, name); }
int GetId() const { return id; }
};
int main() {
Student s(1001, "Alice");
s.Print();
Student* p = new Student(1002, "Bob");
p->Print();
delete p;
return 0;
}
類與物件是 C++ 面向物件程式設計的基石。掌握類的定義、存取控制、成員函數實作、物件建立與銷毀,是進階學習繼承、多型、範本、STL 等特性的前提。