首先明确一点:
系统已经提供了默认的 拷贝构造函数 和 =复制运算符。 即所谓的浅拷贝。
但有时,我们必须提供自己重写。一般是在有指针的情况下重写。
举个简单的例子,没有指针,其实不必重写,只是为了演示:
[cpp]
class Fraction{
private:
int fenmu; //分母
int fenzi; //分子
public:
Fraction(int x,int y){
fenzi = x;
fenmu = y;
}
Fraction(){}
Fraction(const Fraction & fr);
Fraction & operator=(Fraction& p);
void display(){
cout << fenmu << " " << fenzi;
}
};
Fraction::Fraction(const Fraction & fr){
cout << "test: use copy" << endl;
fenmu = fr.fenmu;
fenzi = fr.fenzi;
}
Fraction & Fraction::operator=(Fraction& fr){
if(this == &fr)
return *this;
fenmu = fr.fenmu;
fenzi = fr.fenzi;
cout << "test use =" << endl;
return *this;
}
int main(){
Fraction f(1,2);
Fraction f2(f); //use copy
//f2.display();
Fraction f3 = f2; // use copy
Fraction f4,f5;
f5 = f4 = f3; // use =
//f5.display();
return 0;
}
output:
[cpp]
test: use copy
test: use copy
test use =
test use =
如果有指针,则需要深拷贝:
[cpp] view plaincopyprint
#include <iostream>
using namespace std;
class CA
{
public:
CA(int b,char* cstr)
{
a=b;
str=new char[b];
strcpy(str,cstr);
}
CA(const CA& C)
{
a=C.a;
str=new char[a]; //深拷贝
if(str!=0)
strcpy(str,C.str);
}
void Show()
{
cout<<str<<endl;
}
~CA()
{
delete str;
}
private:
int a;
char *str;
};
int main()
{
CA A(10,"Hello!");
CA B=A;
B.Show();
return 0;
}