多个图表统计的网站怎么做b2b电子商务平台排名
析构函数
析构函数于构造函数相对应,构造函数是对象创建的时候自动调用的,而析构函数就是对象在销毁的时候自动调用的
特点:
1)构造函数可以有多个来构成重载,但析构函数只能有一个,不能构成重载
2)构造函数可以有参数,但析构函数不能有参数
3)与构造函数相同的是,如果我们没有显式的写出析构函数,那么编译器也会自动的给我们加上一个析构函数,什么都不做;如果我们显式的写了析构函数,那么将会覆盖默认的析构函数
4)在主函数中,析构函数的执行在return
语句之前,这也说明主函数结束的标志是return
,return
执行完后主函数也就执行完了,就算return
后面还有其他的语句,也不会执行的
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson op1;system("pause");return 0;
}
运行结果
Beginning
从这里也可以发现,此时析构函数并没有被执行,它在system
之后,return
之前执行
指针对象执行析构函数
与栈区普通对象不同,堆区指针对象并不会自己主动执行析构函数,就算运行到主函数结束,指针对象的析构函数也不会被执行,只有使用delete
才会触发析构函数
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson *op2 = new Cperson;delete(op2);system("pause");return 0;
}
运行结果
Beginning
End
在这里可以发现,已经出现了End
,说明析构函数已经被执行,也就说明了delete
触发了析构函数
临时对象
格式:类名();
作用域只有这一条语句,相当于只执行了一个构造函数和一个析构函数
除了临时对象,也有临时变量,例如语句int(12);
就是一个临时变量,当这句语句执行完了,变量也就释放了,对外部没有任何影响,我们可以通过一个变量来接受这一个临时的变量,例如:int a=int(12);
这与int a=12;
不同,后者是直接将一个整型数值赋给变量a
,而前者是先创建一个临时的变量,然后再将这个变量赋给变量a
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){cout << "Beginning" << endl;}~Cperson(){cout << "End" << endl;}
};int main()
{Cperson();system("pause");return 0;
}
运行结果
Beginning
End
析构函数的作用
当我们在类中声明了一些指针变量时,我们一般就在析构函数中进行释放空间,因为系统并不会释放指针变量指向的空间,我们需要自己来delete
,而一般这个delete
就放在析构函数里面
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){pp = new int;cout << "Beginning" << endl;}~Cperson(){delete pp;cout << "End" << endl;}private:int *pp;
};int main()
{Cperson();system("pause");return 0;
}
malloc、free和new、delete的区别
malloc
不会触发构造函数,但new
可以
free
不会触发析构函数,但delete
可以
#include <iostream>
#include <string>
using namespace std;class Cperson
{
public:Cperson(){pp = new int;cout << "Beginning" << endl;}~Cperson(){delete pp;cout << "End" << endl;}private:int *pp;
};int main()
{Cperson *op1 = (Cperson *)malloc(sizeof(Cperson));free(op1);Cperson *op2 = new Cperson;delete op2;system("pause");return 0;
}
运行结果
Beginning
End
从结果上来看,只得到了一组Beginning、End
说明只有一组触发了构造函数和析构函数,这一组就是new和delete