按值传递和引用传递的区别

按值传递:在方法中使用这个变量将会复制一个临时变量,返回时会销毁这个临时变量

引用传递:不需要创建临时变量和销毁临时变量,节约时间和空间,如果可以选择,优先选择引用传递

 
#include"stdio.h"
#include <iostream>
using namespace std;
class CopyTest
{
private :
	char *name;
	int len;
	static int  num_name;
public:
	CopyTest();
	CopyTest(char *str);
	~CopyTest();
friend std::ostream & operator<<(std::ostream &os,const CopyTest  &st);
//	getName();
	CopyTest(CopyTest & copyA);
};
CopyTest::CopyTest()
{
	cout<<"使用copyTest()创建"<<"\n";
	num_name++;
	len=4 ;
	name=new char[len];
	strcpy(name,"c++");
	
}
int CopyTest::num_name=0;
CopyTest::CopyTest(CopyTest & copyA)
{
	cout<<"使用copyTest(CopyTest & copyA)创建"<<copyA.name<<"\n";
	num_name++;
	len=copyA.len ;
	name=new char[len+1];
	strcpy(name,copyA.name);	
}
CopyTest::CopyTest(char *str)
{
	cout<<"使用copyTest(char *str)创建"<<str<<"\n";
	num_name++;
	len=strlen(str);
	name=new char[len+1];
	strcpy(name,str);	
}
CopyTest::~CopyTest()
{
	cout<<"销毁"<<name<<"\n";
	num_name--;
}
void getName(CopyTest sb)
{
	cout<<"name:"<<sb<<"\n";
}

std::ostream &  operator<<(std::ostream  & os,const CopyTest &st)
{
	os<<st.name ;
	return os;
}
int main()
{
   CopyTest test("test");
   getName1(test);//在getName中使用CopyTest时先调用复制构造函数创建一个临时的CopyTest,返回时调用析构方法销毁这个临时的CopyTest
   cout<<test;
	getchar();
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值