c++封装:类和对象实现封装;
作用:提高代码的维护性,保证代码的独立性(高内聚低耦合)
编译器调用时会加上变量的地址
定义一个对象就会生成一个this指针:指向当前操作的对象
为什么需要this指针:因为同一个类实例的对象共享代码段(方法),为了区分访问哪个对象的成员,所以编译器会在编译阶段给类的所有方法加上this指针参数,用来指向当前操作的对象;
构造函数
构造函数:用来初始化对象的成员的值
引入的作用:防止忘记初始化
特点:
1、函数名与类名相同
2、没有返回值
3、可以重载
4、自动调用
构造函数的种类:
1、默认的无参构造函数
2、有参构造函数
3、拷贝构造函数
4、类型转换构造函数
5、移动拷贝构造函数
无参构造函数:调用无参构造函数:默认的无参构造函数(类里没有任何构造函数时,系统会默认生成)Test t;
Test() = default;
声明无参构造函数使用系统默认生成的;
Test() = delete;
不让系统默认生成无参构造函数
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
this->name = nullptr;
cout << "Test" << endl;
}
//Test() = default; //声明无参构造函数使用系统默认生成的;
//Test() = delete;//不让系统默认生成无参构造函数
int num;
char* name;
int age;
};
int main()
{
Test t;
return 0;
}
有参构造函数:可以重载
#include<iostream>
using namespace std;
class Test
{
public:
Test(int num,char *name ,int age)
{
this->num = num;
this->age = age;
//this->name=name;//error
int len = strlen(name);
this->name = new char[len + 1];
strcpy(this->name, name);
cout << "Test int char* int" << endl;
}
Test(int num, int age)
{
this->num = num;
this->age = age;
this->name = nullptr;
cout << "Test int int" << endl;
}
int num;
char* name;
int age;
};
int main()
{
Test t1(1, "zhangsan", 21);//有参构造函数
Test t2(2,23);
return 0;
}
拷贝构造函数 : 用已有的对象初始化新的对象
默认拷贝构造函数(问题:浅拷贝问题)
自定义拷贝构造函数(深拷贝)
拷贝构造函数的调用时机:
1、用已有的对象初始化新的对象
2、传参:当形参为类的对象时,传参时会调用拷贝构造函数
3、函数返回值为对象时;
#include<iostream>
using namespace std;
class Test
{
public:
Test(int num,char *name ,int age)
{
this->num = num;
this->age = age;
//this->name=name;//error
int len = strlen(name);
this->name = new char[len + 1];
strcpy(this->name, name);
cout << "Test int char* int" << endl;
}
Test(const Test& other)
{
this->age = other.age;
this->num = other.num;
int len = strlen(other.name);
this->name = new char[len + 1];
strcpy(this-> name, other.name);
cout << "Test copy Test" << endl;
}
void test1(Test t)
{
cout << t.name << endl;
}
Test test2()
{
Test temp(1, "lisi", 24);
return temp;
}
int num;
char* name;
int age;
};
int main()
{
Test t1(1, "zhangsan", 21);
Test t3(t1);//用已有的对象初始化新的对象
cout << t3.name << "" << t3.num << endl;
test1(t1);//传参:当形参为类的对象时,传参时会调用拷贝构造函数
Test t2 = test2();//函数返回值为对象时;
return 0;
}
类型转换构造函数:构造函数只有一个参数的,都是类型转换构造函数;
用explicit防止发生类型转换
//定义在class里
explicit Test(int num) //防止发生隐式转换
{
this->num = 0;
this->age = 0;
this->name = nullptr;
cout << "Test int" << endl;
}
explicit Test(const char* name)
{
this->name = nullptr;
this->num = 0;
this->age = 0;
}
//下面为main函数里的内容
//Test t4 = 1; //调用类型转换构造函数! 危险(隐式类型转换:其他可以转换成类类型)
Test t5(1);
//Test t6 = "hello world";
Test t7;
//t7 = 1;
移动拷贝构造函数: 解决临时对象拷贝效率问题
//定义在class里
Test(Test&& other)//移动拷贝拷贝构造函数
{
this->num = other.num;
this->age = other.age;
this->name = other.name;
other.name = nullptr;
cout << "Test copy Test &&" << endl;
}
//在main里
Test(t1);
析构函数
析构函数:释放对象成员所分配的内存空间
引入的目的:防止内存泄露
特点:
1、函数名是 ~类名
2、无参
3、不可重载
4、没有返回值
5、当对象被释放,会先调用析构函数
//在class里
~Test()
{
if (name != nullptr)
{
delete[] name;
}
cout << "~Test" << endl;
}