上后谈爱情

导航

 

1.拷贝构造函数:用已经创建对象初始化新的对象,首先是一个构造函数,在调用时候产生对象,通过参数传递对其进行初始化

2.赋值运算函数:operator():将一个对象赋值给一个原有对象,所以原有的对象中的内存必须进行释放同时判断两个对象是是不是同一个对象

  1 /*赋值运算符号*/
  2 #include<iostream>
  3 #include<string>
  4 using namespace std;
  5 
  6 class CMyString
  7 {
  8 private:
  9     char* m_pdata;
 10 public:
 11     /*对函数声明*/
 12     CMyString (char *pData=NULL);
 13     CMyString(const CMyString& str);
 14     ~CMyString(void);
 15     /*operator 赋值函数,同时声明返回值类型才能够连续进行赋值引用,返回类型引用*/
 16     CMyString& operator=(const CMyString &str);
 17     void Print(); 
 18 };
 19 
 20 /*-------------------在类外对函数进行补充------------------*/
 21 /*构造函数*/
 22 CMyString::CMyString(char *pData)
 23 {
 24     if(pData==NULL)
 25     {
 26         m_pdata=new char[1];
 27         m_pdata='\0';
 28     }
 29     else
 30     {
 31         int length=strlen(pData);
 32         m_pdata=new char[length+1];
 33         strcpy(m_pdata,pData);
 34     }
 35  
 36 }
 37 
 38 /*拷贝构造函数*/
 39 CMyString::CMyString(const CMyString& str)
 40   {
 41       m_pdata=str.m_pdata; 
 42           
 43  }
 44 void CMyString::Print()  
 45 {  
 46     cout<<m_pdata<<endl;  
 47 }  
 48 CMyString::~CMyString()  
 49 {  
 50     delete []m_pdata;  
 51 }  
 52 
 53 /*操作函数 返回该值引用,程序会自动执行这一个操作数函数*/
 54 CMyString& CMyString::operator=(const CMyString &str)
 55 {
 56     /*if(this==&str)
 57     {
 58         return *this;
 59     }
 60     
 61     /*释放已经有的内存*/
 62         /*delete []m_pdata;
 63         m_pdata=NULL;
 64         */
 65         /*为了防止出现异常安全性,采用零时实例方式,不采用new char 和strcopy,在其中加入一项保持实例有效型*/
 66                   if(this!=&str)
 67           {      //加入这段程序在出现无缘无故中断情况,
 68                  CMyString strTemp(str);
 69                 /*保存原有实例现在赋值实例*/
 70                  char*  pTemp=strTemp.m_pdata;
 71                   strTemp.m_pdata=m_pdata;
 72                   m_pdata=pTemp;
 73                   
 74            }
 75         //m_pdata = new char[strlen(str.m_pdata)+1];  
 76        // strcpy(m_pdata,str.m_pdata); 
 77     
 78     return *this;
 79 }
 80 
 81 void test1()//普通赋值  
 82 {  
 83     cout<<"test1() begins:"<<endl;  
 84     char *text = "hello world";  
 85     CMyString str1(text);  
 86     CMyString str2;  
 87     str2 =str1;  
 88   
 89     cout<<"The expected result is: "<<text<<endl;  
 90     cout<<"the actual result is: "<<endl;  
 91     str2.Print();  
 92   
 93     cout<<endl;  
 94 }  
 95 int main()
 96 {
 97     test1();
 98     return 0;
 99 
100 }

 

posted on 2017-03-01 11:41  上后谈爱情  阅读(184)  评论(0编辑  收藏  举报