⏱ 70 分钟 | 前置:第 18 课(类与封装)、第 15 课(new/delete)| 工具:VSCode + g++
: 成员(值), 成员(值) 给成员变量开出生证明this 指针:区分同名参数与成员,看懂链式调用 a.deposit(10).deposit(20)| 时间 | 环节 |
|---|---|
| 0–5 分钟 | 复习第 18 课 + 作业讲评(重点讲 private 校验与类外定义) |
| 5–17 分钟 | 知识点1:构造函数——出生自带装备 |
| 17–27 分钟 | 知识点2:初始化列表 |
| 27–42 分钟 | 知识点3:析构函数与生老病死的顺序(本课重头戏) |
| 42–50 分钟 | 知识点4:this 指针与链式调用(简介) |
| 50–63 分钟 | 课堂练习 |
| 63–70 分钟 | 总结 + 布置作业 |
Student s; 造出来时 double score 里是垃圾值——忘了调 setScore 就直接用,程序就带着脏数据跑。总不能靠"记得调用"这种人品保证吧?C++ 给了正解:构造函数——对象"出生"那一刻自动执行的函数。三条家规:函数名与类名相同、没有返回类型(连 void 都不写)、创建对象时自动调用。
#include <iostream>
#include <string>
using namespace std;
class BankAccount {
string owner;
double balance;
public:
BankAccount(string name, double b) { // 与类同名,没有返回类型
owner = name;
balance = b;
cout << "创建 " << owner << " 的账户,余额 " << balance << endl;
}
double getBalance() { return balance; }
};
int main() {
BankAccount a("张三", 0); // 创建 张三 的账户,余额 0
BankAccount b("李四", 100); // 创建 李四 的账户,余额 100
cout << b.getBalance() << endl; // 100
return 0;
}void BankAccount(...) 编译报错 return type specification for constructor invalid;BankAccount c; 报错 no matching function for call to 'BankAccount()'。想两种创建姿势都有?自己再补一个无参的 BankAccount() { ... }。构造函数体里的"先出生再赋值"其实分两步。正经写法是初始化列表:在参数表后加冒号,一口气把成员全部落好户口:
class Account2 {
string owner;
double balance;
const int id; // const 成员:一旦定了永不再改
public:
Account2(string name, double b, int i) : owner(name), balance(b), id(i) {
cout << "创建 " << owner << " 的账户,余额 " << balance << endl;
}
};读法:: owner(name), balance(b), id(i)——"出生时 owner 直接用 name 初始化、balance 直接用 b……"。平时和函数体里赋值效果一样,但有一位必须用它:
Account2(...) { id = i; },编译报错 uninitialized const member in 'const int'——const 变量出生就得有值,而初始化列表正是"出生那一刻"。军规:构造函数一律优先写初始化列表,顺手还快一点。有出生就有退场。析构函数:名字是 ~类名()(波浪线读作"滴——"),无参数无返回值,对象销毁前自动执行——正是第 15 课"delete 之前要还内存"的官方收尸人。
#include <iostream>
#include <string>
using namespace std;
class Account2 {
string owner;
double balance;
public:
Account2(string name, double b) : owner(name), balance(b) {
cout << "创建 " << owner << " 的账户,余额 " << balance << endl;
}
~Account2() {
cout << "销毁 " << owner << " 的账户" << endl;
}
void deposit(double amt) { balance += amt; cout << owner << " 存入 " << amt << endl; }
double getBalance() { return balance; }
};
int main() {
Account2 a("张三", 0); // ① 创建 张三 的账户,余额 0
{
Account2 b("李四", 100); // ② 创建 李四 的账户,余额 100
a.deposit(50); // ③ 张三 存入 50
} // ④ 小作用域结束 → 销毁 李四 的账户
cout << "a balance=" << a.getBalance() << endl; // ⑤ a balance=50
return 0; // ⑥ main 结束 → 销毁 张三 的账户
}栈对象自动生灭;堆上 new 出来的对象,delete 那一刻才喊析构——生杀大权在你手里:
int main() {
Account2* h = new Account2("王五", 10); // 创建 王五 的账户,余额 10
delete h; // 销毁 王五 的账户 ← 析构在这里执行
return 0; // 若忘写 delete?程序结束悄悄泄漏,析构都轮不上
}new 签约、delete 退租,忘了退租就一直烧房租(内存泄漏),而且退租时析构函数会帮你打扫房间(善后清理)。上节课留的悬念揭晓:成员函数没传参却认识 r、balance,因为编译器偷偷递给它一个 this——"我自己的地址"。平时不用写它,但两种场合要见面:
class Account3 {
string owner;
double balance = 0;
public:
Account3(string owner) {
this->owner = owner; // 参数和成员同名:this-> 指名"我的"owner
}
Account3& deposit(double amt) { // 返回"我自己"的引用 → 可以接着点下去
balance += amt;
cout << owner << " 存入 " << amt << endl;
return *this;
}
double getBalance() { return balance; }
};
int main() {
Account3 a("张三");
a.deposit(10).deposit(20); // 张三 存入 10 / 张三 存入 20
cout << "a chain=" << a.getBalance() << endl; // a chain=80
return 0;
}this 是指向"本对象"的隐藏指针(第 13 课老朋友上岗);this-> 就是"我自己的…",专治参数撞名return *this;(把自己交出去)→ 返回值是引用,点号可以链式接力:存入10 再存入20,实测余额 80Student:带参构造 Student(string n, double s) 和无参构造 Student()(户口名"新生"、分数 0),两者都 cout 一句出生报告。main 里各造一个验证。顺手做实验:删掉无参构造再编译 Student m;,亲眼看看那句报错。
#include <iostream>
#include <string>
using namespace std;
class Student {
string name;
double score;
public:
Student(string n, double s) : name(n), score(s) {
cout << "老生报到:" << name << " " << score << endl;
}
Student() : name("新生"), score(0) {
cout << "新生入学(默认值)" << endl;
}
void show() { cout << name << " " << score << endl; }
};
int main() {
Student a("张三", 92); // 老生报到:张三 92
Student m; // 新生入学(默认值)
a.show(); // 张三 92
m.show(); // 新生 0
return 0;
}Robot:构造输出"机器人 X 启动"、析构输出"机器人 X 下线"。main 剧本:先声明 r1("一号");开一个小花括号再声明 r2("二号"),花括号结束后用 new 造 r3("三号") 再立刻 delete;走到 main 结尾。先在纸上写 6 行输出预测,再编译对答案。
Log 类:private int count = 0;write(string msg) 输出 msg、count 加一,并 return *this;。main 里一句 log.write("起床").write("上课").write("写代码"); 连打三卡,最后 cout << "今日 " << log.count << " 条"(自己加个 getCount)。
class Log {
int count = 0;
public:
Log& write(string msg) {
cout << "[记录] " << msg << endl;
count++;
return *this;
}
int getCount() { return count; }
};
int main() {
Log log;
log.write("起床").write("上课").write("写代码");
// [记录] 起床 / [记录] 上课 / [记录] 写代码
cout << "今日 " << log.getCount() << " 条" << endl; // 今日 3 条
return 0;
}Clock:带参构造 Clock(int h, int m, int s)(用初始化列表),非法值(时 0~23、分秒 0~59 之外)时输出"非法时间,已归零"并全存 0;show() 不足 10 在前面补 0,输出如 08:30:05(不许用新头文件,用 if 判断就行)。剧本:Clock a(8,30,5) → 08:30:05;Clock b(25,0,0) → 归零 00:00:00。
class Clock {
int h, m, s;
public:
Clock(int hh, int mm, int ss) : h(0), m(0), s(0) { // 先全部落户口
if (hh >= 0 && hh <= 23 && mm >= 0 && mm <= 59 && ss >= 0 && ss <= 59) {
h = hh; m = mm; s = ss;
} else {
cout << "非法时间,已归零" << endl;
}
}
void pad(int x) { if (x < 10) cout << "0"; cout << x; } // 补零小工
void show() { pad(h); cout << ":"; pad(m); cout << ":"; pad(s); cout << endl; }
};
int main() {
Clock a(8, 30, 5);
a.show(); // 08:30:05
Clock b(25, 0, 0);
b.show(); // 非法时间,已归零 → 00:00:00
return 0;
}new Robot("铁皮") 造出来,先别 delete,跑一遍记下输出;再补上 delete 跑第二遍对比。思考题:两遍输出差哪行?"下线"没打印时,对象去哪了?
#include <iostream>
#include <string>
using namespace std;
class Account {
string owner;
double balance;
const int id;
public:
void Account(string name, double b, int i) { // A
owner = name;
balance = b;
id = i; // B
}
void setOwner(string owner) { owner = owner; } // C
double getBalance() { return balance; }
};
int main() {
Account a("张三", 100, 1);
Account b; // D
cout << a.getBalance() << endl;
return 0;
}void Account(...) 编译报错 return type specification for constructor invalid,删掉 void;② B:const 成员不能在函数体里赋值——报错 uninitialized const member,必须走初始化列表:Account(...) : id(i) { ... }(owner、balance 也顺手进列表更规范);③ C:参数撞名自己抄自己——owner = owner 是参数赋给自己,成员纹丝不动,写 this->owner = owner;(或不给参数重名);④ D:写了带参构造就没有默认无参构造——Account b; 报错 no matching function for call to 'Account()',要么补一个 Account() : id(0) { ... },要么这行改成带参创建。: 成员(值), ... 是出生时落户口;const 成员只能走这里~类名():销毁前自动跑,栈对象出作用域、堆对象 delete 时各谢幕一次this = 本对象地址:this-> 治参数撞名;return *this; 玩链式调用