class Test
{
public:
Test(int a = 5, int b = 5) // Test(); Test(10); Test(10, 10);
{
ma = a;
mb = b;
cout << "Test(int, int)" << " ma:" << ma << "mb:" << mb << endl;
}
~Test()
{
cout << "~Test()" << " ma:" << ma << "mb:" << mb << endl;
}
Test(const Test &src)
{
ma = src.ma;
mb = src.mb;
cout << "Test(const Test&)" << " ma:" << ma << "mb:" << mb << endl;
}
void operator=(const Test &src)
{
ma = src.ma;
mb = src.mb;
cout << "operator=" << " ma:" << ma << "mb:" << mb << endl;
}
private:
int ma;
int mb;
};
Test t1(10, 10);
int main()
{
Test t2(20, 20);//调用带两个参数的构造函数构建并且初始化对象t2,先是分配内存并且用this指针指向这块内存,再用两个实参初始化
Test t3 = t2;//t2拷贝构造函数构建对象t3
static Test t4 = Test(30, 30);//优化之后,用构造临时对象的方法,直接构建对象t4并且用30,30初始化
t2 = Test(40, 40);//调用构造此种构造函数创建临时对象,并且调用赋值运算符的重载函数给t2赋值,在语句结束时,调用析构函数结束临时对象
t2 = (Test)(50, 50); // Test(50, 5);//逗号表达式,相当于(Test)50,传过去之后再带一个默认参数5,显示构造临时对象,其他跟上句一样
t2 = 60; // Test(60, 5);隐式构建临时对象,其他跟上句一样
Test *p1 = new Test(70, 70); //在堆上构建对象并且初始化,用p1指针指向这块内存, new2 ->它对调用合适的构造函数 malloc1
Test *p2 = new Test[2]; //Test[2],在堆上构建两个对象 new Type[10]; new 堆上构造对象数组的时候不能进行初始化
Test *p3 = &Test(80, 80);//构建临时对象,指针指向这个对象
Test &p4 = Test(90, 90);//p4引用临时对象,临时对象的生命周期等于p4了
delete p1; // -> 一次析构函数 delete2 先调用对象的析构函数《-释放内存之前 free1
delete[]p2; // 两次析构函数
//system("pause");
return 0;
}
Test t5(100, 100);
运行结果:
Test(int, int) ma:10mb:10
Test(int, int) ma:100mb:100
Test(int, int) ma:20mb:20
Test(const Test&) ma:20mb:20
Test(int, int) ma:30mb:30
Test(int, int) ma:40mb:40
operator= ma:40mb:40
~Test() ma:40mb:40
Test(int, int) ma:50mb:5
operator= ma:50mb:5
~Test() ma:50mb:5
Test(int, int) ma:60mb:5
operator= ma:60mb:5
~Test() ma:60mb:5
Test(int, int) ma:70mb:70
Test(int, int) ma:5mb:5
Test(int, int) ma:5mb:5
Test(int, int) ma:80mb:80
~Test() ma:80mb:80
Test(int, int) ma:90mb:90
~Test() ma:70mb:70
~Test() ma:5mb:5
~Test() ma:5mb:5
~Test() ma:90mb:90
~Test() ma:20mb:20
~Test() ma:60mb:5
~Test() ma:30mb:30
~Test() ma:100mb:100
~Test() ma:10mb:10
请按任意键继续…