#include <iostream>
using namespace std;
/*
二个特殊的构造函数
1)默认无参构造函数
当类中没有定义构造函数时,编译器默认提供一个无参构造函数,并且
其函数体为空
2)默认拷贝构造函数
当类中没有定义拷贝构造函数时,编译器默认提供一个默认拷贝构造函
数,简单的进行成员变量的值复制
*/
class Test
{
public:
Test()
{
cout << "无参构造" << endl;
}
Test(int a) :m_a(a)
{
cout << "有参构造" << endl;
}
Test(const Test &another)
{
m_a = another.m_a;
cout << "拷贝构造" << endl;
}
void test_print(void)
{
cout << "m_a:" << m_a << endl;
}
~Test()
{
cout << "析构函数" << endl;
}
private:
int m_a;
};
//拷贝构造的第一种场景:用对象1初始化对象2
void test1(void)
{
cout << "test1:xxxxxxxxxxxxxxxxxxxxxxxxxx" << endl;
Test t1(10);
Test t2 = t1; //用 t1 初始化t2
t2.test_print();
cout << "test1: end xxxxxxxxxxxxxxxxxxxxx" << endl;
}
//拷贝构造的第二种场景:
void test2(void)
{
cout << endl;
cout << endl;
cout << "test2:xxxxxxxxxxxxxxxxx" << endl;
Test t1(20);
Test t2(t1);
t2.test_print();
cout << "test2: end xxxxxxxxxxxxxxxxxx" << endl;
}
//拷贝构造的第三种场景: 函数传参时会调用拷贝构造
void fun(Test t)
{
cout << "fun begin" << endl;
t.test_print();
cout << "fun end" << endl;
}
void test3(void)
{
cout << endl;
cout << endl;
cout << "test3:xxxxxxxxxxxxxxxxx" << endl;
Test t1(30);
Test t2 = t1; //调用一次拷贝构造
fun(t2); //这里 t = t2 还会调用一次拷贝构造
cout << "test3: end xxxxxxxxxxxxxxxxxx" << endl;
}
//拷贝构造的第四种场景: 需要用几个测试函数来说明
Test return_obj(void)
{
cout << "return_obj begin" << endl;
Test t1(40);
cout << "return_obj end" << endl;
return t1; //这里会返回一个新的匿名对象,所以会调用匿名对象的拷贝构造函数
}
//return_obj()返回一个新的匿名对象,所以会调用一次拷贝构造函数
void test4_1(void)
{
cout << endl;
cout << endl;
cout << "test4_1:xxxxxxxxxxxxxxxxx" << endl;
return_obj();
cout << "test4_1: end xxxxxxxxxxxxxxxxxx" << endl;
}
//如果⽤匿名对象 初始化 另外⼀个同类型的对象, 匿名对象 转成有名对象
void test4_2(void)
{
cout << endl;
cout << endl;
cout << "test4_2:xxxxxxxxxxxxxxxxx" << endl;
Test t1 = return_obj();
t1.test_print();
cout << "test4_2: end xxxxxxxxxxxxxxxxxx" << endl;
}
//如果⽤匿名对象 赋值给 另外⼀个同类型的对象, 匿名对象 被析构
void test4_3(void)
{
cout << endl;
cout << endl;
cout << "test4_3:xxxxxxxxxxxxxxxxx" << endl;
Test t1(43);
t1 = return_obj();
t1.test_print();
cout << "test4_3: end xxxxxxxxxxxxxxxxxx" << endl;
}
int main()
{
test1();
test2();
test3();
test4_1();
test4_2();
test4_3();
return 0;
}
运行结果: