構造函數在創建對象時自動調用,用於初始化成員;析構函數在對象銷毀時自動調用,釋放資源。兩者均無返回值,名字分別為類名與 ~類名。
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
// 使用初始化列表
Student(string name, int age, float score)
: name(name), age(age), score(score) {}
~Student() { cout << name << "再見" << endl; }
void say() const { cout << name << "的年齡是 " << age << ",成績是 " << score << endl; }
private:
string name;
int age;
float score;
};
int main() {
Student s1("小明", 15, 90.5f);
Student s2("李磊", 16, 95);
Student s3("王爽", 16, 80.5f);
s1.say(); s2.say(); s3.say();
cout << "main 即將結束" << endl;
return 0;
}
輸出順序:三個 say()、main 即將結束、三個析構函數(逆序銷毀)。
常引用參數 const T& 兼具「避免拷貝」與「防止修改」優勢:
#include <iostream>
using namespace std;
class Time {
public:
Time(int h, int m, int s) : hour(h), minute(m), sec(s) {}
int hour, minute, sec;
};
// 常引用參數
void printTime(const Time& t) {
cout << t.hour << ':' << t.minute << ':' << t.sec << endl;
}
int main() {
Time t1(10, 13, 56);
printTime(t1); // 傳遞左值
printTime(Time(12, 0, 0)); // 傳遞右值臨時對象,合法
return 0;
}