📌 當你用 class
建立一個物件時,它會自動被呼叫,用來「初始化」物件
#include <iostream>
using namespace std;
class Student
{
private:
string name;
int age;
public:
Student(string n, int a)
{
name = n;
age = a;
cout << "建立學生: " << name << endl;
}
void display()
{
cout << "姓名: " << name << ", 年齡: " << age << endl;
}
};
int main()
{
Student s1("小A", 12);
Student s2("小B", 13);
s1.display();
s2.display();
return 0;
}
當物件「消失」時(例如程式結束、物件超出範圍)
解構函式會自動被呼叫
📌 用來釋放資源(例如關閉檔案、釋放記憶體)
~類別名稱
#include <iostream>
using namespace std;
class Student
{
private:
string name;
public:
Student(string n)
{
name = n;
cout << "建立學生: " << name << endl;
}
~Student()
{
cout << "刪除資料: " << name << endl;
}
};
int main()
{
Student s1("小A");
Student s2("小B");
return 0;
}
📌 建構函式 → 負責在物件建立時進行初始化
例如設定初始值或配置資源
📌 解構函式 → 在物件消失時釋放資源或進行清理
避免記憶體外洩或資源未關閉的問題