#include<iostream>
#include<stdio.h>
using namespace std;
class Test
{
public:
Test(int a = 5, int b = 5) :ma(a), mb(b)
{
cout << this << " Test("<<a<<" "<<b<<")" << endl;
}
~Test()
{
cout << this << "~Test()" << endl;
}
Test(const Test &src)
{
cout << this << "Test(const Test&)" << endl;
}
void operator=(const Test &src)
{
cout << this << "operator=" << endl;
}
int getValue(){ return ma; }
private:
int ma;
int mb;
};
Test t1(10, 10);
int main()
{
Test t2(20, 20);//Test t2(20,20);
Test t3=t2;//不产生临时对象,调用拷贝构造;
static Test t4 = Test(30, 30);//不产生临时对象,编译器的优化==>t3(20,5);
t2 = Test(40, 40);//产生临时对象Test(40,40)然后调用赋值函数最后临时对象析构
t2 = (Test)(50, 50);//产生临时对象Test(50,5)然后调用赋值函数最后临时对象析构
t2 = 60;//产生临时对象Test(60,5)然后调用赋值函数最后临时对象析构
Test *p1 = new Test(70, 70);//调用构造函数Test(70,70)
Test *p2 = new Test[3];//调用20次构造函数Test(5,5)
Test *p3 = &Test(80, 80);//先调用临时对象Test(80,80),对象地址赋值给p3临时对象析构
Test &p4 = Test(90, 90);//先调用临时对象Test(90,90),对象作为引用给p4,
//临时对象获取名字后不析构,相当转正
delete p1;//p1指向的临时对象析构
delete []p2;//p2指向的对象数组析构,和构造顺序相反
}
Test t5(100, 100);
对象的生存周期探究
最新推荐文章于 2024-08-16 23:42:34 发布