#include<iostream>
using namespace std;
//拷贝构造函数调用时机
class Person
{
public:
int m_age;
Person()
{
cout<<"Person的默认构造函数"<<endl;
}
Person(int age)
{
cout<<"Person的有参构造函数"<<endl;
m_age=age;
}
Person(const Person &p)
{
cout<<"Person的拷贝构造函数"<<endl;
m_age=p.m_age;
}
~Person()
{
cout<<"Person的析构函数"<<endl;
}
};
//1、使用一个已经创建完毕的对象来初始化一个新对象
void test02()
{
Person p1(20);
Person p2(p1);
cout<<p2.m_age<<endl;
}
//2、值传递的方式给函数参数传值
void doWork(Person p)
{
}
void test01()
{
Person p;
doWork(p);
}
//3.以值方式返回局部对象 (dev-c++没有此拷贝构造函数)
Person doWork2()
{
Person p;
return p;
}
void test03()
{
Person p = doWork2();
}
int main()
{
test02();
cout<<"------------------"<<endl;
test01();
cout<<"------------------"<<endl;
test03();
return 0;
}
C++复习之拷贝构造函数调用时机
最新推荐文章于 2024-06-25 21:35:06 发布