一、封装
封装的写法并不唯一,在实际的过程中会结合业务需求而定,下面的以一个最基础的案例进行编写。通常先对属性私有化,使属性隐藏,然后根据当前属性的需求,通过getter函数和setter函数对类外分别公开读和写的功能。
#include <iostream>
using namespace std;
class MobilePhone
{
private: // 私有权限:只有类内部可访问
string brand; // 可读可写
string model; // 只写
int weight = 188; // 初始值
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;
}
};
int main()
{
MobilePhone mp1;
mp1.set_brand("小米");
mp1.set_model("13 Pro");
cout << mp1.get_brand() << " " << mp1.get_weight() << endl;
MobilePhone* mp2 = new MobilePhone;
mp2->set_brand("红米");
mp2->set_model("K60 Pro");
cout << mp2->get_brand() << " " << mp2->get_weight() << endl;
delete mp2;
return 0;
}
二、构造函数
构造函数类内一种特殊的函数,用来创建一个对象。如果一个类中,程序员不手动编写构造函数,编译器会为这个类自动添加一个无参构造函数,且此函数的函数体为空;如果程序员手写了任意一个构造函数,编译器就不再自动添加构造函数了。
#include <iostream>
using namespace std;
class MobilePhone
{
private:
string brand;
string model;
int weight;
public:
// MobilePhone(){} // 编译器自动添加的无参构造函数
MobilePhone() // 手写构造函数
{
// 可以设定属性的默认值
brand = "山寨";
model = "8848钛金手机";
weight = 188;
cout << "生产了一部手机" << endl;
}
string get_brand()
{
return brand;
}
void set_brand(string b)
{
brand = b;
}
void set_model(string m)
{
model = m;
}
int get_weight()
{
return weight;
}
};
int main()
{
MobilePhone mp1; // 调用了无参构造函数
mp1.set_brand("小米");
mp1.set_model("13 Pro");
cout << mp1.get_brand() << " " << mp1.get_weight() << endl;
MobilePhone* mp2 = new MobilePhone; // 调用了无参构造函数
mp2->set_brand("红米");
mp2->set_model("K60 Pro");
cout << mp2->get_brand() << " " << mp2->get_weight() << endl;
delete mp2;
return 0;
}
三、拷贝构造函数
如果程序员在一个类中不手动编写拷贝构造函数,编译器会为这个类自动添加一个拷贝构造函数,拷贝构造函数与普通构造函数也是函数重载的关系,对象和对象之间是独立存在的实体,数据也是相互独立的,拷贝构造函数可以把一个对象的属性值拷贝到新创建的对象中。
#include <iostream>
using namespace std;
class MobilePhone
{
private:
string brand;
string model;
int weight;
public:
MobilePhone(string b,string m,int w)
:brand(b),model(m),weight(w)
{}
// 编译器自动添加的拷贝构造函数
// MobilePhone(const MobilePhone& mp)
// {
// brand = mp.brand;
// model = mp.model;
// weight = mp.weight;
// }
void show()
{
cout << brand << " " << model << " "
<< weight << endl;
cout << &brand << " " << &model << " "
<< &weight << endl;
}
};
int main()
{
MobilePhone mp1("小米","13Pro",190);
mp1.show();
// 拷贝构造函数
MobilePhone mp2(mp1);
mp2.show();
return 0;
}
四、析构函数
构造函数 | 析构函数 |
手动调用 | 在对象被销毁时自动调用 |
通常用于在对象创建时初始化 | 通常用于在对象销毁时回收资源 |
可以被重载 | 不可以重载,因为没有参数 |
函数名是类名 | 函数名是~类名 |
#include <iostream>
using namespace std;
class Cat
{
public:
~Cat()
{
cout << "猫挂了" << endl;
}
};
int main()
{
cout << "主函数开始" << endl;
// Cat c1;
Cat* c2 = new Cat;
delete c2;
cout << "主函数结束" << endl;
return 0;
}