码迷,mamicode.com
首页 > 其他好文 > 详细

深复制、浅复制

时间:2019-06-05 09:35:41      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:set   cout   int   etc   ios   delete   tst   cst   use   

#include <iostream>

using namespace std;

class CDemo {
public:
  CDemo(int pa,char *cstr)
  {
    this->a = pa;
    this->str = new char[104];
    strcpy(this->str,cstr);
    //this->str = cstr;
  }

  int getA()
  {
    return this->a;
  }

  char* getCStr()
  {
    return this->str;
  }

  void setA(int a)
  {
    this->a = a;
  }

  void setStr(char *cstr)
  {
    this->str = new char[104];
    strcpy(this->str, cstr);
  }

  void setStr2(char *cstr)
  {
    this->str = cstr;
  }

  ~CDemo()
  {
    delete str;
  }
private:
  int a;
  char *str;
};

 

int main()
{
  CDemo A(10,"hello");
  cout <<"A:"<< A.getA()<<" "<<A.getCStr()<< endl;

  CDemo B = A;
  cout << "B:" << B.getA() << " " << B.getCStr() << endl;

  B.setA(30);
  B.setStr("word");//深复制
  //B.setStr2("word2");//浅复制

  cout << "B:" << B.getA() << " " << B.getCStr() << endl;
  cout << "A:" << A.getA() << " " << A.getCStr() << endl;


  system("pause");
  return 0;
}

 

-----------------------------------------------------------------------------------------------------

A:10 hello
B:10 hello
B:10 word
A:10 hello
请按任意键继续. . .

深复制、浅复制

标签:set   cout   int   etc   ios   delete   tst   cst   use   

原文地址:https://www.cnblogs.com/herd/p/10977573.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!