欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

詳解C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)

 編寫類String 的構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù),已知類String 的原型為:

class String
{
public:
String(const char *str = NULL); // 普通構(gòu)造函數(shù)
String(const String &other); // 拷貝構(gòu)造函數(shù)
~ String(void); // 析構(gòu)函數(shù)
String & operate =(const String &other); // 賦值函數(shù)
private:
char *m_data; // 用于保存字符串
}; 

#include <iostream> 
class String 
{ 
public: 
  String(const char *str=NULL);//普通構(gòu)造函數(shù) 
  String(const String &str);//拷貝構(gòu)造函數(shù) 
  String & operator =(const String &str);//賦值函數(shù) 
  ~String();//析構(gòu)函數(shù) 
protected: 
private: 
  char* m_data;//用于保存字符串 
}; 
 
//普通構(gòu)造函數(shù) 
String::String(const char *str)
{ 
  if (str==NULL)
  { 
    m_data=new char[1]; //對空字符串自動申請存放結(jié)束標(biāo)志'\0'的空間 
    if (m_data==NULL)
    {//內(nèi)存是否申請成功 
     std::cout<<"申請內(nèi)存失敗!"<<std::endl; 
     exit(1); 
    } 
    m_data[0]='\0'; 
  } 
  else
  { 
    int length=strlen(str); 
    m_data=new char[length+1]; 
    if (m_data==NULL)
    {//內(nèi)存是否申請成功 
      std::cout<<"申請內(nèi)存失??!"<<std::endl; 
      exit(1); 
    } 
    strcpy(m_data,str); 
  } 
} 

//拷貝構(gòu)造函數(shù) 
String::String(const String &other)
{ //輸入?yún)?shù)為const型 
  int length=strlen(other.m_data); 
  m_data=new char[length+1]; 
  if (m_data==NULL)
  {//內(nèi)存是否申請成功 
    std::cout<<"申請內(nèi)存失??!"<<std::endl; 
    exit(1); 
  } 
  strcpy(m_data,other.m_data); 
} 

//賦值函數(shù) 
String& String::operator =(const String &other)
{//輸入?yún)?shù)為const型 
  if (this == &other) //檢查自賦值 
  { return *this; }

  delete [] m_data;//釋放原來的內(nèi)存資源 

  int length=strlen(other.m_data);   
  m_data= new char[length+1]; 
  if (m_data==NULL)
  {//內(nèi)存是否申請成功 
    std::cout<<"申請內(nèi)存失??!"<<std::endl; 
    exit(1); 
  } 
  strcpy(m_data,other.m_data); 

  return *this;//返回本對象的引用 
} 

//析構(gòu)函數(shù) 
String::~String()
{ 
  delete [] m_data; 
} 
 
void main()
{ 
  String a; 
  String b("abc"); 
  system("pause"); 
} 

以上就是C++ 編寫String 的構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)的實(shí)例,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有