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

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

C語言

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

C++實(shí)現(xiàn)String類實(shí)例代碼

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

C++實(shí)現(xiàn)String類實(shí)例代碼

這是一道十分經(jīng)典的面試題,可以短時(shí)間內(nèi)考查學(xué)生對C++的掌握是否全面,答案要包括C++類的多數(shù)知識,保證編寫的String類可以完成賦值、拷貝、定義變量等功能。

#include<iostream> 
using namespace std; 
 
class String 
{ 
public: 
    String(const char *str=NULL); 
    String(const String &other); 
    ~String(void); 
    String &operator =(const String &other); 
private: 
    char *m_data; 
}; 
 
String::String(const char *str) 
{ 
  cout<<"構(gòu)造函數(shù)被調(diào)用了"<<endl; 
  if(str==NULL)//避免出現(xiàn)野指針,如String b;如果沒有這句話,就會出現(xiàn)野 
         //指針 
  { 
    m_data=new char[1]; 
    *m_data=''/0''; 
  } 
  else 
  { 
   int length=strlen(str); 
   m_data=new char[length+1]; 
   strcpy(m_data,str); 
  } 
} 
String::~String(void) 
{ 
  delete m_data; 
  cout<<"析構(gòu)函數(shù)被調(diào)用了"<<endl; 
} 
 
String::String(const String &other) 
{ 
 cout<<"賦值構(gòu)造函被調(diào)用了"<<endl; 
 int length=strlen(other.m_data); 
 m_data=new char[length+1]; 
 strcpy(m_data,other.m_data); 
} 
String &String::operator=(const String &other) 
{ 
   cout<<"賦值函數(shù)被調(diào)用了"<<endl; 
   if(this==&other)//自己拷貝自己就不用拷貝了 
         return *this; 
   delete m_data;//刪除被賦值對象中指針變量指向的前一個(gè)內(nèi)存空間,避免 
          //內(nèi)存泄漏 
   int length=strlen(other.m_data);//計(jì)算長度 
   m_data=new char[length+1];//申請空間 
   strcpy(m_data,other.m_data);//拷貝 
   return *this; 
} 
void main() 
{ 
   String b;//調(diào)用構(gòu)造函數(shù) 
   String a("Hello");//調(diào)用構(gòu)造函數(shù) 
   String c("World");//調(diào)用構(gòu)造函數(shù) 
   String d=a;//調(diào)用賦值構(gòu)造函數(shù),因?yàn)槭窃赿對象建立的過程中用a來初始化 
   d=c;//調(diào)用重載后的賦值函數(shù) 
} 

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

上一篇:用C++類實(shí)現(xiàn)單向鏈表的增刪查和反轉(zhuǎn)操作方法

欄    目:C語言

下一篇:C++中的異常處理機(jī)制詳解

本文標(biāo)題:C++實(shí)現(xiàn)String類實(shí)例代碼

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/1649.html

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

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

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

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