很久没有用C++了,今天看到一道关于赋值与拷贝的面试题,准备写几句代码验证下。
首先,讲下验证过后的结论:
1)显示调用拷贝构造函数,肯定会执行拷贝构造函数。如Cat c2(c1);
2)在初使化时进行赋值,也会执行拷贝构造函数,如Cat c2=c1;
3)其它时间进行赋值,执行operator=的实现函数。如Cat c1,c2; c1=c2;
代码如下所示:
#include <iostream>
using namespace std;
class Cat{
public:
char name[20];
public:
Cat(){}
Cat(char * s){
if(s!=NULL)
strcpy(name,s);
cout<<"use constructor"<<endl;
}
Cat(const Cat & cat)
{
if(cat.name!=NULL)
strcpy(name,cat.name);
cout<<"use copy constrctor"<<endl;
}
Cat & operator=(Cat& cat)
{
if(this == &cat)
return *this;
strcpy(name,cat.name);
cout<<"use operator ="<<endl;
return *this;
}
};
int main(){
Cat c1("there is a cat"); //use constructor
Cat c2(c1); //use copy constructor
Cat c3 = c2; // use copy constructor
Cat c4,c5;
c5= c4 = c3; // use operator =
return 0;
}
下面粘贴下结果: