设为首页 加入收藏

TOP

C++拷贝构造函数和=赋值运算符(一)
2013-01-13 10:31:03 来源: 作者: 【 】 浏览:552
Tags:拷贝 构造 函数 运算

  首先明确一点:

  系统已经提供了默认的 拷贝构造函数 和  =复制运算符。 即所谓的浅拷贝。

  但有时,我们必须提供自己重写。一般是在有指针的情况下重写。

  举个简单的例子,没有指针,其实不必重写,只是为了演示:

  [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;

  }

   

首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇SO_REUSEADDR例解 下一篇端口重用 C++(地址重用)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: