1、匿名对象声明周期--复习
没人接匿名对象
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
using namespace std;
class Test1{
public:
Test1(int a,int b,int c)
{
this->m_a = a;
this->m_b = b;
this->m_c = c;
cout<<"有参构造函数Test1 "<<this->m_a<<" "<<this->m_b<<" "<<this->m_c<<endl;
}
~Test1()
{
cout<<"~Test1()析构函数Test1 "<<this->m_a<<" "<<this->m_b<<" "<<this->m_c<<endl;
}
public:
int getA()
{
return this->m_a;
}
private:
int m_a;
int m_b;
int m_c;
};
class Test2{
public:
//C++中提供初始化列表对成员变量进行初始化
//Test2中组合了Test1的对象,并且Test1的对象 有构造函数
//Test1有了构造函数必须使用,就出现构造函数的初始化列表
Test2():t1(1,2,3),t2(4,5,6),c(100)
{
cout<<"Test2有参构造函数1"<<endl;
}
Test2(const Test2 &obj):t1(11,22,33),t2(44,55,66),c(99)//拷贝构造函数也可以用构造函数列表
{
cout<<"有参构造函数2"<<endl;
}
~Test2()
{
cout<<"析构造函数Test2 "<<endl;
}
public:
Test1 t1;
Test1 t2;//c++编译器不知道如何构造t1和t2
const int c;//用const属性必须要用初始化列表初始化
};
int doThing(Test2 mye1)
{
printf("doThing() mye1.abc1.a:%d \n", mye1.t1.getA());
return 0;
}
int objplaymain(){
//Test1 t1(10);
//参数传递
//Test2 obj1(5,6);
//(1)先执行被组合对象的构造函数,组合对象有多个 按照定义的顺序去调用,不是按照初始化列表的顺序
//(2)析构函数的调用顺序和构造函数相反
Test2 myT2;
doThing(myT2);//是一个元素,实参初始化形参,会调用拷贝构造函数
return 0;
}
int objplaymain2()
{
printf("objplaymain2 start..\n");
Test1(400, 500, 600); //匿名对象的生命周期 :没人接马上就析构了
//Test1 abcd = Test1(100, 200, 300);
//若直接调用构造函数呢?
//想调用构造函数对abc对象进行再复制,可以吗?
//在构造函数里面调用另外一个构造函数,会有什么结果?
printf("objplaymain2 end\n");
return 0;
}
int main()
{
objplaymain2();
cout<<"hello...."<<endl;
system("pause");
return 0;
}
没人接匿名对象
有人接匿名对象