C++ 第四天

一、this指针
1.1 什么是this 指针
指向当前对象的指针
构造函数中this指向正在被构建的对象首地址
成员函数中 this代表调用这个函数的对象的首地址
1.2 this指针的应用
区分成员变量 和函数参数
this 可以作为函数参数
this 可以作为返回值(实现连续操作)
二、const对象和const函数
const对象就是加了const修饰对象
const A a;
const 函数就是加了const修饰的成员函数
class A{
public:
void show()const{
/*这就是const函数*/
}
void show(){
/*这就是非const函数*/
}
};
1.2 规则
const 函数和非const函数可以构成重载关系
const 对象只能调用const函数
const 函数中只能读成员变量 不能修改成员变量的值 也不能调用非const的成员函数
如果非要在const函数中去修改成员变量 只要在修饰的成员变量上 加一个mutable修饰
非const对象优先调用非const函数,如果没有非const函数则调用const函数。
#include <iostream>
using namespcae std;
class A{
mutable int data;
public:
/*_ZK1A4showEv*/
void show(){
cout << "show()" << endl;
}
/*_ZNK1A4showEv*/
void show()const{
cout << "show()const" << endl;
data=1101;
cout << data << endl;
}
}
int main(){
A var_a;
var_a.show();
const A var_b=var_a;
var_b.show();
}

三、析构函数
3.1析构函数和构造函数同名 在函数名前加~,这个函数是无参的所以一个类型中
只有一个析构函数
3.2作用
可以在一个对象销毁之前 自动调用一次。
用来释放内存 释放资源
3.3 内存相关的两个操作
构造函数 分配内存
析构函数 释放内存
#include <iostream>
using namespcae std;
class A{
int *data;
public:
/*构造函数中分配内存*/
A():data(new int(10)){
/*data= new int(10)*/
cout << "A()" << endl;
}
/*析构函数 负责释放内存*/
~A(){
cout << "~A()" << endl;
delete data;
}
};
int main(){
A *pa = new A[5];//创建5个对象
delete[] pa;
}

四.new delete 比malloc free
new 比malloc多做了一些事
1、如果类型中有类类型的成员 new会自动构建这个成员
2、new 会自动处理类型转换
3、new 会自动调用构造函数
delete 比free多调用了一次析构函数
#include <iostream>
using namespcae std;
struct Date{
int year;
int month;
int day;
Date(){
cout << "Date()" << endl;
}
~Date(){
cout << "~Date()" << endl;
}
};
class Person{
int age;
Date date;
public:
Person(){
cout << "Person()" << endl;
}
~Person(){
cout << "~Person()" << endl;
}
};
int main(){
Person *p=static_cast<Person*>malloc(sizeof(Person));
free(p);
Person *p2 = new Person();
delete p2;
}

猜你喜欢

转载自www.cnblogs.com/Malphite/p/9904077.html