C++封装

面向对象的三大特性:封装 → 继承 → 多态

封装:将类的一些属性和其他细节隐藏,重新提供给外部调用的接口。类似于测试中白盒与黑盒的概念。

 

提供给外部访问隐藏的属性接口通常分为两种

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,永远是一个默认值,因此引入构造函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值