构造了一个Test的类
代码如下:
//
// Created by yanpan on 2019/4/21.
//
#if 1
#include <iostream>
using namespace std;
class Test
{
public:
Test(int a = 10, int b = 10):_a(a),_b(b) //带有默认值的构造函数
{
cout << this << endl;
cout << "a: " << _a << " b: " << _b << endl;
cout << "test()" << endl;
};
Test(const Test &src) //拷贝构造函数
{
_a = src._a;
_b = src._b;
cout << &src << "->" << this << endl;
cout << "a: " << _a << " b: " << _b << endl;
cout << "test(const test &src)" << endl;
}
void operator=(const Test &src) //赋值运算符重载函数
{
_a = src._a;
_b = src._b;
cout << &src << "->" << this << endl;
cout << "a: " << _a << " b: " << _b << endl;
cout << "operator=(const test &src))" << endl;
}
~Test() //析构函数
{
cout << this << endl;
cout << "a: " << _a << " b: " << _b << endl;
cout << "~Test()" << endl;
}
private:
int _a;
int _b;
};
Test test1(20,10);
int main()
{
Test test2(20, 20);
Test test3 = test2;
static Test test4 = Test(40, 40);//初始化的静态局部变量在.data段存储,程序的存活周期就是静态变量的生存周期
test2 = Test(50, 50);
test2 = (Test)(60, 60);
test2 = 70; //隐式生成临时对象
Test *p1 = &Test(80); //用指针指向临时对象,出了语句临时对象会析构
Test &q1 = Test(90, 50); //引用变量引用临时对象,临时对象的生存周期和引用变量的生存周期一样
Test *p2 = new Test;
delete p2;
return 0;
}
Test test5(100, 100);
#endif
- 调用构造函数 构造test1
- 调用构造函数 构造test5
- 调用构造函数 构造test2
- 调用拷贝构造函数 拷贝构造test3
- 调用构造函数构造静态局部对象test4(test4的存储在.data段)
- 调用构造函数构造Test(50, 50)临时对象, 将临时对象赋值给test2,临时对象析构
- 调用构造函数构造Test(60, 10)临时对象 ps:逗号表达式了解一下, 将临时对象赋值给test2,析构临时对象
- 调用构造函数构造Test(70, 10)临时对象 隐式生成临时对象 是常对象 ps:赋值重载函数的参数设置为const的原因之一,将临时对象赋值给test2,析构临时对象
- 调用构造函数构造Test(80, 10)临时对象 用指针p1指向临时对象,但临时对象除了语句就会析构,所以除了函数调用的情况外,不要用指针指向临时对象;
- 调用构造函数构造Test(90, 50)临时对象 用引用变量q1引用生成的临时对象,临时对象出了语句不析构,和引用变量的生存周期一样
- 用指针p2指向在堆上调用构造函数构造一个堆上的对象, 调用delete 则调用析构函数析构堆上的对象,释放内存
- 结下调用析构函数,依次析构q1引用的临时对象、析构test3、析构test2、析构test4、析构test5、析构test1
运行结果
00190218
a: 20 b: 10
test()
00190220
a: 100 b: 100
test()
00CFFC48
a: 20 b: 20
test()
00CFFC48->00CFFC38
a: 20 b: 20
test(const test &src)
0019022C
a: 40 b: 40
test()
00CFFAC8
a: 50 b: 50
test()
00CFFAC8->00CFFC48
a: 50 b: 50
operator=(const test &src))
00CFFAC8
a: 50 b: 50
~Test()
00CFFAD8
a: 60 b: 10
test()
00CFFAD8->00CFFC48
a: 60 b: 10
operator=(const test &src))
00CFFAD8
a: 60 b: 10
~Test()
00CFFAE8
a: 70 b: 10
test()
00CFFAE8->00CFFC48
a: 70 b: 10
operator=(const test &src))
00CFFAE8
a: 70 b: 10
~Test()
00CFFAF8
a: 80 b: 10
test()
00CFFAF8
a: 80 b: 10
~Test()
00CFFC10
a: 90 b: 50
test()
0101DF50
a: 10 b: 10
test()
0101DF50
a: 10 b: 10
~Test()
00CFFC10
a: 90 b: 50
~Test()
00CFFC38
a: 20 b: 20
~Test()
00CFFC48
a: 70 b: 10
~Test()
0019022C
a: 40 b: 40
~Test()
00190220
a: 100 b: 100
~Test()
00190218
a: 20 b: 10
~Test()
请按任意键继续. . .