1.类的构造函数
class Test
{
public:
//无参构造函数
Test()
{
cout << "无参构造函数" << endl;
}
//有参构造函数
Test(int a,int b)
{
cout << "有参构造函数" << endl;
}
//赋值或者拷贝构造函数
Test(const Test & t)
{
cout << "赋值或者拷贝构造函数" << endl;
}
private:
};
void main()
{
Test t;//这里调用了无参构造
Test t2(1,2);//这里调用有参构造函数
Test t3=Test(1, 2);
//这里也调用有参构造函数,相当于先创建一个匿名对象,然后在转成t3;也就是t3对象初始化
t = t3;//这个调用了t的拷贝构造函数;
system("pause");
}
初始化尽量放在构造函数中,有些情况就没有机会初始化了;
2.拷贝构造函数的几种调用场景
class Test
{
public:
int a;
//无参构造函数
Test()
{
cout << "无参构造函数" << endl;
}
//有参构造函数
Test(int a,int b)
{
cout << "有参构造函数" << endl;
}
//赋值或者拷贝构造函数
Test(const Test & t)
{
cout << "赋值或者拷贝构造函数" << endl;
}
~Test()
{
cout << "调用了析构函数" << endl;
}
void setObjiect(Test tt)
{
}
private:
};
Test getObject()
{
Test t;
t.a = 10;
return t;//在这里创建了一个匿名对象返回去,使用已有对象创出化匿名对象,调用匿名对象的拷贝构造函数
//在调用了t的析构函数,把匿名对象返回去,如果发现返回去没有人接受,所以把匿名对象也析构了,调用析构函数;
}
void main(){
Test t;//这里调用了无参构造
//Test t