C++复习之拷贝构造函数调用时机

2023-12-29 06:09:45
#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;
}
 

文章来源:https://blog.csdn.net/weixin_51615604/article/details/135273991
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。