- 拷贝构造函数调用时机
点击查看代码
#include<iostream>
#include<string>
using namespace std;
//拷贝构造函数调用时机
//1、使用一个已经创建完毕的对象来初始化一个新对象
//2、值传递的方式给函数参数传值
//3、值方式返回局部对象
class Person
{
public:
//普通构造函数
Person()
{
cout << "Person 无参构造函数的调用" << endl;
}
Person(int age)
{
m_age = age;
cout << "Person 有参构造函数的调用" << endl;
}
//拷贝构造函数
Person(const Person &p)
{
m_age = p.m_age;
cout << "Person 拷贝构造函数的调用" << endl;
}
//析构函数
~Person()
{
cout << "Person 析构函数的调用" << endl;
}
int m_age;
};
//1、使用一个已经创建完毕的对象来初始化一个新对象
void test01()
{
Person p1(10);
Person p2(p1);
cout << "p2的年龄为:" << p2.m_age << endl;
}
//2、值传递的方式给函数参数传值
void func1(Person p)
{
}
void test02()
{
Person p1(10);
func1(p1);
}
//3、值方式返回局部对象
Person func2()
{
Person p2; //局部对象
return p2; //值方式返回,不是返回p2本身。返回时,根据p2创建一个新对象,返回给test03
}
void test03()
{
Person p3 = func2();
}
int main(){
test01();
cout << "***********test01************" << endl;
test02();
cout << "***********test02************" << endl;
test03();
cout << "***********test03************" << endl;
system("pause");
return 0;
}