类会默认产生的成员函数
說明:代碼來自<<程序員面試寶典>>
?
#include<iostream> using namespace std;class String { public:String(const char *str);//構造函數,str是傳入的參數~String();//析構函數String(const String &other);//拷貝構造函數String& operator=(const String &other);//賦值函數 private:char *m_data; };String::String(const char *str) {if(NULL==str)//沒有傳入字符串{m_data=new char[1];//申請一個空間來存放\0,表示空串*m_data='\0';}else{m_data=new char[strlen(str)+1];strcpy(m_data,str); //將字符串內容復制到指針所指向的內存空間 } }String::~String() {delete []m_data; }String::String(const String &other)//相當于對一個新的實例進行初始化化,other表示提供值的哪一個實例 {if(other.m_data==NULL)//判斷指針是否為空{m_data=new char[1];*m_data='\0';}else{m_data=new char[strlen(other.m_data)+1];//中間要求指針指向的那個字符的長度strcpy(m_data,other.m_data);} }String::String::operator=(const String &other)//賦值函數 {//檢查自賦值if(this==&other)return *this;//釋放原因內存資源delete []m_data;//分配新的內存資源,并復制內容int length=strlen(other.m_data);m_data=new char[length+1];strcpy(m_data,other.m_data);return *this;//返回本對象的引用 }C++中的賦值和拷貝:
?
拷貝:對未初始化的內存進行初始化工作。
String s1("hello"); ? ?String s2(s1)//或String s2=s1;
賦值:對已初始化的內存進行再操作(重新賦值)
String s1("hello"); ? ?String s2; ? ?String s2=s1;//s2已經被初始化過了,只不過初始化為空
?
int length=strlen(other.m_data)計算的是指針所指字符串長度而不是指針的長度。
注意sizeof和strlen
sizeof;C語言中判斷數據類型或者表達式長度符(計算占用空間),是一個運算符,字節數的計算在程序的編譯時進行,而不是在程序的執行過程中才算出來。(百度百科)
strlen:一個用來計數的函數,接收一個char *作為參數,碰到'\0'結束。所以必須是計算以'\0'結尾的(不包括'\0')。
?
#include<iostream> using namespace std;int main() {char *str="123456";cout<<str<<endl;//123456cout<<sizeof(str)<<endl;//4,計算的指針的長度cout<<strlen(str)<<endl;//6,計算指針指向的字符串的長度,不包括'\0'char str1[]="123456";cout<<str1<<endl;cout<<sizeof(str1)<<endl;//7,計算整個字符串長度,包括'\0'(計算占用空間)cout<<sizeof(str1)<<endl;//6return 0; }注意字符數組和指針指向的數組的區別。strlen一樣,sizeof不一樣。
?
?
賦值函數里面參數是cosnt
當other為const時,一個const變量不能隨意轉化為非const變量(拷貝構造函數也一樣)。
String s3(hello);
Const string s4(haha);
s3=s4;
?
再看一段代碼:
?
#include<iostream> using namespace std;class Parent {public:Parent(char *str,int var=-1)//帶有默認實參的要在后面{m_data=str;n=var;}void getn(){cout<<n<<endl;}void getChar(){cout<<m_data<<endl;} private:int n;char *m_data; };class child:public Parent {public:child(char *str,int var=1):Parent(str)//初始化父類的指針變量{n=var;}void getn(){cout<<n<<endl;} private:int n; };int main() {char *str="123";child c1(str);c1.getn();//1 c1.Parent::getn();//-1c1.getChar();//123return 0; }父類的函數和變量不會因為同名而被子類覆蓋,父類指針變量要指明初始化,其他變量可默認。
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的类会默认产生的成员函数的全部內容,希望文章能夠幫你解決所遇到的問題。