日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++空类和string类

發(fā)布時間:2023/12/13 c/c++ 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++空类和string类 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

1. 空類

1.1 空類默認哪六個成員函數(shù)。

1 class Empty 2 { 3 public: 4 Empty(); //缺省構造函數(shù) Empty e; 5 Empty( const Empty& ); //拷貝構造函數(shù) Empty e2(e1); 6 ~Empty(); //析構函數(shù) 7 Empty& operator=( const Empty& ); //賦值運算符 Empty e2 = e1; 8 Empty* operator&(); //取址運算符 &e 9 const Empty* operator&() const; //取址運算符const &e 10 };

?

1.2 空類的sizeof()=1

每個實例在內(nèi)存中都有一個獨一無二的地址,為了達到這個目的,編譯器往往會給一個空類隱含的加一個字節(jié),這樣空類在實例化后在內(nèi)存得到了獨一無二的地址。

2. string類

以下四個函數(shù),是C++編譯器會自動加入的四個函數(shù)。

1 class MyString 2 { 3 public: 4 MyString(const char *str = NULL);//默認參數(shù),不傳遞的該參數(shù)的時候發(fā)揮作用。 5 MyString(const MyString &other); 6 MyString& operator=(const MyString &other); 7 ~MyString(); 8 private: 9 char *m_data; 10 }; 11 MyString::~MyString() 12 { 13 delete [] m_data; 14 } 15 MyString::MyString(const char *str) 16 { 17 if(NULL == str) 18 { cout<<"調(diào)用普通構造函數(shù)1"<<endl; 19 m_data = new char[1]; 20 *m_data = '\0'; 21 } 22 else 23 { 24 cout<<"調(diào)用普通構造函數(shù)2"<<endl; 25 size_t length = strlen(str); 26 m_data = new char[length+1]; 27 strcpy(m_data,str); 28 } 29 } 30 MyString::MyString(const MyString &other) 31 { cout<<"調(diào)用拷貝構造函數(shù)"<<endl; 32 size_t length = strlen(other.m_data); 33 m_data = new char[length+1]; 34 strcpy(m_data,other.m_data); 35 } 36 MyString& MyString::operator =(const MyString &other) 37 { 38 cout<<"調(diào)用賦值函數(shù)"<<endl; 39 //檢查自賦值 40 if(this == &other) 41 return *this; 42 //釋放原有的內(nèi)存資源 43 delete [] m_data; 44 int length = strlen(other.m_data); 45 m_data = new char[length+1]; 46 strcpy(m_data,other.m_data); 47 return *this; 48 } 49 int _tmain(int argc, _TCHAR* argv[]) 50 { 51 MyString s0;//"調(diào)用普通構造函數(shù)1" 52 MyString s1 = "hi";//"調(diào)用普通構造函數(shù)2" 53 MyString s2("hi");//"調(diào)用普通構造函數(shù)2" 54 55 MyString s3 = s1;//"調(diào)用拷貝構造函數(shù)"上述實現(xiàn)為深拷貝。 56 MyString s4(s2);//"調(diào)用拷貝構造函數(shù)" 57 s4 = "hello!";//將"hello!"傳入賦值函數(shù)形參時,要調(diào)用普通構造函數(shù)2;接著調(diào)用賦值函數(shù)。 58 s4 = s3;//"調(diào)用賦值函數(shù)" 59 return 0; 60 }

總結:僅定義對象或者傳遞對象的時候調(diào)用構造函數(shù)。

說明:拷貝構造函數(shù)必須傳引用。調(diào)用拷貝構造函數(shù)如果傳值,編譯器會新開辟一段棧內(nèi)存,建立此對象的臨時拷貝,而建立臨時拷貝又需要值傳遞調(diào)用拷貝構造函數(shù),如此

進入死循環(huán),直至內(nèi)存耗盡死機。而傳引用則無需新開辟內(nèi)存空間,無需調(diào)用構造函數(shù),形參對象只是另一個對象的別名。

?

轉(zhuǎn)載于:https://www.cnblogs.com/shijianchuzhenzhi/p/4419255.html

總結

以上是生活随笔為你收集整理的C++空类和string类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。