struct:默認 public (成員、繼承)。class:默認 private (成員)、private 繼承。class Student {
int id;
string name;
public:
// 推薦:直接初始化成員,避免默認構造+賦值雙重開銷
Student(int id, const string& name) : id(id), name(name) {}
// 傳統寫法 (低效)
// Student(int id, const string& name) { this->id = id; this->name = name; }
};
類管理**動態記憶體、文件句柄、Socket、鎖**等獨享資源時 (遵循 **Rule of Three/Five/Zero**)。
class Student {
char* name; // 動態分配
public:
Student(const char* n) { name = strdup(n); }
// 拷貝構造
Student(const Student& other) : name(strdup(other.name)) {}
// 拷貝賦值 (Copy-and-swap 惯用法)
Student& operator=(Student other) { swap(name, other.name); return *this; }
~Student() { free(name); }
};
int& ref = a; → ref 是 a 的別名,**不佔用額外存儲**。new T / new T[N]:分配記憶體並調用構造函數。delete ptr / delete[] arr:調用析構函數並釋放記憶體。std::unique_ptr, std::shared_ptr, std::vector, std::string 等 RAII 容器/智能指針。Student s1(1001, "Zhang"); // 直接初始化
Student s2 = 1001; // 複制初始化 (調用 Student(int) 構造,非拷貝構造)
Student s3 = s1; // 複制初始化 (調用拷貝構造)
=delete 禁用拷貝,配合移動語義)。const/引用成員**必須**在列表初始化。const T&,需修改用 T&,所有權轉移用智能指針按值傳遞。struct/class 僅默認可見性不同,按團隊風格統一 (如:POD 用 struct,行為類用 class)。