按值传递:在方法中使用这个变量将会复制一个临时变量,返回时会销毁这个临时变量
引用传递:不需要创建临时变量和销毁临时变量,节约时间和空间,如果可以选择,优先选择引用传递
#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;
}