深色模式
第 13 章:类与对象(上)——为什么要面向对象
本章能学到什么
- 结构体「只管数据不管行为」带来的麻烦
- 类 = 数据 + 行为的打包
- 构造函数与析构函数
- 成员函数和普通函数的区别
- public / private 的意义
知识链位置:第 12 章用结构体把学生的数据捆成了一包。本章再进一步:把操作这些数据的函数也装进包里。这是编程思想的一次升级。
场景:数据和操作分家的麻烦
第 12 章的程序里,结构体管数据,函数管操作,两边是分开的:
cpp
struct Student {
string name;
int chinese;
int math;
};
int total(const Student& s) { // 操作写在结构体外面
return s.chinese + s.math;
}程序小的时候没问题。程序变大后,麻烦出现了:
- 项目里有十几种结构体,几十个散落的函数。
total到底是给哪种包用的,只能靠命名和记忆区分。 - 外部代码可以随意写
s.chinese = -50,没人拦得住。负数分数是非法数据,但结构体不会自我保护。 - 想把成绩从「分数」改成「等级制」,所有直接碰过
chinese的代码都要找出来改。
问题的根源:数据和它的操作分家了。它们明明是一体的,却住在两个地方。
类:把数据和行为装进同一个包
类(class)就是升级版的结构体:除了数据,还能装函数。装进类的函数叫成员函数,表示「这个数据包自己会做的事」。
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public: // public:外面的代码可以用
string name; // 数据部分(成员变量)
int chinese;
int math;
int total() { // 行为部分(成员函数)
return chinese + math; // 直接用包里的数据,不用传参
}
void introduce() {
cout << "我是" << name << ",两科总分" << total() << endl;
}
};
int main() {
Student ming;
ming.name = "小明";
ming.chinese = 88;
ming.math = 92;
ming.introduce(); // 让小明这个包自己介绍自己
return 0;
}text
我是小明,两科总分180变化是本质性的:total() 不再是「外面的函数接过一包数据」,而是「小明这个包自己会算总分」。数据和操作住在同一个家里了。
| 概念 | 含义 | 类比 |
|---|---|---|
| 类(class) | 数据 + 行为的图纸 | 月饼模具 |
| 对象(object) | 照图纸造出的一个具体实例 | 压出来的一块月饼 |
| 成员变量 | 对象里的数据 | 月饼的馅料 |
| 成员函数 | 对象会做的事 | 月饼上印的「福」字功能——开玩笑,是它自带的本领 |
一个月饼模具能压出无数块月饼。一个 Student 类也能造出无数个学生对象,每个对象有自己的姓名和分数。
成员函数 vs 普通函数
| 对比点 | 普通函数 | 成员函数 |
|---|---|---|
| 住在哪里 | 类的外面 | 类的里面 |
| 怎么调用 | total(ming),数据当参数传进去 | ming.total(),对象自己调用 |
| 数据从哪来 | 参数 | 自己包里的成员变量,直接用 |
| 属于谁 | 谁也不属于 | 属于这个类的每一个对象 |
写法上,成员函数内部直接用 chinese、math 这些名字,指的就是「我自己这包里的那两格」。不用传参,也不会拿错包——小明调 total() 算的一定是小明的分。
构造函数:对象出生时的准备
上面先 Student ming; 再造空包、再逐格填数据,有个隐患:填到一半就用,算出来的总分是垃圾值。
构造函数解决这个问题:对象一出生,就把数据填好。它是和类同名的特殊成员函数,造对象时自动执行:
cpp
class Student {
public:
string name;
int chinese;
int math;
Student(string n, int c, int m) { // 构造函数:名字和类相同,没有返回值类型
name = n;
chinese = c;
math = m;
}
int total() {
return chinese + math;
}
};
Student ming("小明", 88, 92); // 出生时就填好,一步到位Student ming("小明", 88, 92); 的意思是:造一个学生对象,同时把三个值交给构造函数。想再造一个空壳学生?编译器不答应——定义了这种构造函数后,造对象就必须给齐数据。非法的「半成品对象」从源头上被杜绝了。
析构函数:对象离开时的收尾
构造函数管出生,析构函数管离开。对象的生命结束(比如离开了它所在的花括号范围)时,析构函数自动执行,适合做收尾工作:
cpp
class Student {
public:
string name;
Student(string n) { // 构造
name = n;
cout << "学生入学:" << name << endl;
}
~Student() { // 析构:类名前面加 ~
cout << "学生毕业:" << name << endl;
}
};
int main() {
Student ming("小明");
cout << "小明在校期间" << endl;
return 0; // main 结束,ming 离开,析构函数自动执行
}text
学生入学:小明
小明在校期间
学生毕业:小明注意输出的顺序:「毕业」这句话不是人写的 return 之前执行的,而是对象销毁时自动执行的。析构函数在释放文件、网络连接等资源时特别有用,入门阶段先知道它的存在即可。
public 与 private:给数据包装上锁
回到开头的麻烦:ming.chinese = -50 这种乱写没人拦得住。private 就是拦它的:
cpp
class Student {
private: // private:只有类内部的函数能碰
int chinese;
int math;
public:
void setScores(int c, int m) {
if (c >= 0 && c <= 100 && m >= 0 && m <= 100) {
chinese = c; // 合法才收
math = m;
} else {
cout << "分数必须在 0~100 之间!" << endl;
}
}
int total() {
return chinese + math;
}
};外面写 ming.chinese = -50,编译直接报错——chinese 是私有的,只有类内部的函数能碰。想改分数,只能走 setScores 这个「窗口」,窗口里有检查。非法数据进不来了。
这就是封装的雏形:把数据锁在包里,只留几个安全的窗口。第 14 章还会专门讲它的意义。
成员函数怎么知道是哪个对象
ming.total() 和 hong.total() 调用的是同一段代码,算出的却是各自的总分。秘密在于:调用成员函数时,对象会悄悄把自己的地址传进去,这个隐藏的指针叫 this。
total() 里的 chinese,编译器实际看到的是 this->chinese——「调用我的那个对象的 chinese」。平时不用写 this,编译器自动补全;需要时写出来,效果完全一样:
cpp
int total() {
return this->chinese + this->math; // 和不写 this 相同
}构造函数可以有好几个
和第 8 章的函数重载一样,构造函数也能准备好几个版本,造对象时按给的参数自动匹配:
cpp
class Student {
public:
string name;
int chinese;
int math;
Student(string n, int c, int m) { // 版本一:信息齐全
name = n; chinese = c; math = m;
}
Student(string n) { // 版本二:只有姓名,成绩记 0
name = n; chinese = 0; math = 0;
}
};
Student ming("小明", 88, 92); // 走版本一
Student temp("插班生"); // 走版本二成绩还没录入的新生,可以先造出来再补数据。每个版本都保证对象「出生即合法」。
class 和 struct 的关系
C++ 里 struct 和 class 几乎是同一个东西:struct 也能装成员函数和构造函数。唯一区别是默认访问级别——struct 的成员默认 public,class 的成员默认 private。
| 写法 | 默认访问级别 | 惯例用法 |
|---|---|---|
struct | public | 纯数据包,如第 12 章的学生信息 |
class | private | 数据 + 行为,强调封装 |
第 12 章用 struct、本章用 class,遵循的就是这个惯例。
完整例子:班级花名册
把本章学到的东西合起来:一个类,一群对象,存在 vector 里统一管理。
cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student {
private:
int chinese;
int math;
public:
string name;
Student(string n, int c, int m) { // 构造函数:出生即合法
name = n;
setScores(c, m); // 走检查窗口,非法分进不来
}
void setScores(int c, int m) {
if (c >= 0 && c <= 100 && m >= 0 && m <= 100) {
chinese = c;
math = m;
} else {
cout << "分数必须在 0~100 之间!" << endl;
chinese = 0;
math = 0;
}
}
int total() {
return chinese + math;
}
void introduce() {
cout << "我是" << name << ",两科总分" << total() << endl;
}
};
int main() {
vector<Student> cls; // 对象组成的容器
cls.push_back(Student("小明", 88, 92));
cls.push_back(Student("小红", 95, 81));
cls.push_back(Student("小刚", 70, 85));
for (int i = 0; i < (int)cls.size(); i++) {
cls[i].introduce();
}
int best = 0; // 找总分最高者
for (int i = 1; i < (int)cls.size(); i++) {
if (cls[i].total() > cls[best].total()) {
best = i;
}
}
cout << "总分最高的是" << cls[best].name << endl;
return 0;
}text
我是小明,两科总分180
我是小红,两科总分176
我是小刚,两科总分155
总分最高的是小明和第 12 章的结构体版本相比:分数锁在 private 里,构造函数保证没有半成品对象,total() 跟着数据走。类的三大好处——打包、初始化、隔离——在这个不到 60 行的程序里全部用上了。
什么该放进类里
设计一个类时,一个简单判断:
| 候选内容 | 放不放 | 理由 |
|---|---|---|
| 描述对象本身的数据(姓名、分数) | 放,作成员变量 | 数据属于对象 |
| 只用到自己数据的操作(算总分) | 放,作成员函数 | 行为贴着数据走 |
| 和具体某个学生无关的操作(比较两个学生谁高) | 可放可不放 | 写成普通函数也合理 |
| 临时计算用的中间变量 | 不放 | 用完就扔,留在函数里 |
【跨语言对照】class、构造函数与访问控制
本质问题:两种语言都要把「数据 + 行为」打包,并且回答「哪些部分允许外面碰」。打包的语法不同,「允许碰」的实现方式更是两种思路。
| 对比点 | C++ | Python |
|---|---|---|
| 类的关键字 | class Student { ... };(结尾有分号) | class Student:(用缩进划界) |
| 构造函数 | 与类同名的函数 Student(...) | 固定名字 __init__(self, ...) |
| 析构函数 | ~Student(),对象销毁时自动执行 | __del__(self),对象被回收时执行,时机不确定 |
| 成员函数的第一参数 | 隐含的,函数里直接用成员名 | 显式写出 self,成员要写成 self.name |
| 私有成员 | private: 真隔离,外面访问会编译报错 | 约定俗成:_name 提示「内部使用」,__name 触发名称改写增加误碰难度,但都能绕过 |
class 定义写法对照。C++:
cpp
class Student {
public:
string name;
Student(string n) { // 构造函数
name = n;
}
void hello() {
cout << "我是" << name << endl;
}
};Python:
python
class Student:
def __init__(self, name): # 构造函数
self.name = name
def hello(self):
print("我是" + self.name)等价代码:造一个学生,让他自我介绍。
C++ 版:
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int chinese;
int math;
Student(string n, int c, int m) { // 构造函数:出生时填好数据
name = n;
chinese = c;
math = m;
cout << "创建了学生:" << name << endl;
}
int total() { // 成员函数:算总分
return chinese + math;
}
void introduce() { // 成员函数:自我介绍
cout << "我是" << name << ",两科总分" << total() << endl;
}
};
int main() {
Student a("小明", 88, 92);
a.introduce();
return 0;
}Python 版(详见 《Python 从入门到精通》第 13 章):
python
class Student:
def __init__(self, name, chinese, math): # 构造函数:出生时填好数据
self.name = name
self.chinese = chinese
self.math = math
print("创建了学生:" + self.name)
def total(self): # 成员函数:算总分
return self.chinese + self.math
def introduce(self): # 成员函数:自我介绍
print("我是" + self.name + ",两科总分" + str(self.total()))
a = Student("小明", 88, 92)
a.introduce()两段程序的输出完全一致:
text
创建了学生:小明
我是小明,两科总分180为什么设计不一样:C++ 把「隔离」做成语言规则,private 成员从外面访问,编译器直接拒绝——规则在程序运行前就生效。Python 的选择是「我们都是成年人」:用下划线命名约定表达意图,信任程序员不去乱碰,换来的是写法和运行时机制的简单。C++ 的 self(它叫 this)藏在幕后,Python 把 self 摆在明面上——一个选择少写字,一个选择少藏东西。两种取向各有适用的场合,下一章还会继续看到这条设计思路的分歧。
动手实验
实验 1:给 Student 类加一个成员函数 average(),返回两科平均分(double 类型)。造出小明并打印他的平均分。
💡 查看答案
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int chinese;
int math;
Student(string n, int c, int m) {
name = n;
chinese = c;
math = m;
}
double average() { // 新增的成员函数
return (chinese + math) / 2.0; // 除以 2.0 得到小数结果
}
};
int main() {
Student ming("小明", 88, 92);
cout << ming.name << "的平均分是" << ming.average() << endl;
return 0;
}text
小明的平均分是90实验 2:用同一个类造出三个学生对象(小明 88/92、小红 95/81、小刚 70/85),放在一个数组里,循环调用 introduce()。
💡 查看答案
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
public:
string name;
int chinese;
int math;
Student(string n, int c, int m) {
name = n;
chinese = c;
math = m;
}
int total() {
return chinese + math;
}
void introduce() {
cout << "我是" << name << ",两科总分" << total() << endl;
}
};
int main() {
Student cls[3] = { // 对象数组:一个月饼模具压三块月饼
Student("小明", 88, 92),
Student("小红", 95, 81),
Student("小刚", 70, 85)
};
for (int i = 0; i < 3; i++) {
cls[i].introduce(); // 每个对象各自介绍自己
}
return 0;
}text
我是小明,两科总分180
我是小红,两科总分176
我是小刚,两科总分155实验 3:把 chinese 和 math 改成 private,配上 setScores 检查。然后在 main 里写 ming.chinese = -50; 试试编译,观察报错,再改用合法的方式设置分数。
💡 查看答案
cpp
#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int chinese;
int math;
public:
string name;
Student(string n) {
name = n;
chinese = 0;
math = 0;
}
void setScores(int c, int m) {
if (c >= 0 && c <= 100 && m >= 0 && m <= 100) {
chinese = c;
math = m;
} else {
cout << "分数必须在 0~100 之间!" << endl;
}
}
int total() {
return chinese + math;
}
};
int main() {
Student ming("小明");
// ming.chinese = -50; // 取消注释会编译报错:chinese 是 private
ming.setScores(-50, 92); // 走窗口:被拒绝
ming.setScores(88, 92); // 走窗口:合法,收下
cout << ming.name << "的总分是" << ming.total() << endl;
return 0;
}text
分数必须在 0~100 之间!
小明的总分是180直接碰 chinese 会在编译期被拦下;走 setScores 窗口,非法值在运行时被拒绝。两道防线各管一段。
