C++實現(xiàn)String類實例代碼
更新時間:2017年04月06日 15:29:01 投稿:lqh
這篇文章主要介紹了C++實現(xiàn)String類實例代碼的相關(guān)資料,需要的朋友可以參考下
C++實現(xiàn)String類實例代碼
這是一道十分經(jīng)典的面試題,可以短時間內(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;//刪除被賦值對象中指針變量指向的前一個內(nèi)存空間,避免 //內(nèi)存泄漏 int length=strlen(other.m_data);//計算長度 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ù),因為是在d對象建立的過程中用a來初始化 d=c;//調(diào)用重載后的賦值函數(shù) }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
C語言編程數(shù)據(jù)結(jié)構(gòu)線性表之順序表和鏈表原理分析
本篇文章是C語言編程篇主要為大家介紹了C語言編程中的數(shù)據(jù)結(jié)構(gòu)線性表,文中附含豐富的圖文示例代碼為大家詳解了線性表中的順序表和鏈表,有需要的朋友可以借鑒參考下2021-09-09C語言調(diào)用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查
SQLite是一種輕量級的關(guān)系型數(shù)據(jù)庫管理系統(tǒng),是一個開源的、零配置的、服務(wù)器端的、自包含的、零管理的、事務(wù)性的SQL數(shù)據(jù)庫引擎,本文主要介紹了如何調(diào)用SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)增刪改查,需要的可以參考一下2023-08-08C++圖像加載之libpng、FreeImage、stb_image詳解
libpng、FreeImage、stb_image都是圖像解析的開源庫,這篇文章主要為大家詳細介紹了這三者的使用方法,文中的示例代碼講解詳細,需要的可以參考一下2023-06-06C語言 如何求兩整數(shù)的最大公約數(shù)與最小公倍數(shù)
這篇文章主要介紹了C語言中如何求兩整數(shù)的最大公約數(shù)與最小公倍數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11