面向对象的三大特性:封装 → 继承 → 多态
封装:将类的一些属性和其他细节隐藏,重新提供给外部调用的接口。类似于测试中白盒与黑盒的概念。
提供给外部访问隐藏的属性接口通常分为两种
setter 用于写入属性值
getter 用于读取属性值
通过这两类公开接口对属性的读写权限分离控制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;
class MobilePhone
{
private: // 私有权限:只能在类内(花括号{}内)访问,隐藏
string brand = "菠萝"; // 可读可写
string model = "14"; // 只写
int weight = 666; // 只读
public:
// 重新开放接口:读写分离管理
string get_brand() // getter可读
{
return brand; //一般返回真实值,也有返回假的
}
void set_brand(string b) // setter可写
{
brand = b;
}
void set_model(string m) // setter可写
{
model = m;
}
int get_weight() // getter
{
return weight;
}
void show()
{
cout << brand << endl;
cout << model << endl;
cout << weight << endl;
}
};
int main()
{
MobilePhone mp1;
mp1.set_brand("华为");
mp1.set_model("P50");
cout << mp1.get_brand() << endl;
cout << mp1.get_weight() << endl; // 默认值
MobilePhone* mp2 = new MobilePhone;
mp2->set_brand("华为");
mp2->set_model("P50");
cout << mp2->get_brand() << endl;
cout << mp2->get_weight() << endl; // 默认值
delete mp2;
return 0;
}
设置的默认值太生硬,每次创建出的对象如果不set,永远是一个默认值,因此引入构造函数