從string類的完成看C++類的四年夜函數(面試罕見)。本站提示廣大學習愛好者:(從string類的完成看C++類的四年夜函數(面試罕見))文章只能為提供參考,不一定能成為您想要的結果。以下是從string類的完成看C++類的四年夜函數(面試罕見)正文
同伙面試的一道面試題,分享給年夜家,面試官常常會問到的,完成string類的四年夜根本函數必控制。
一個C++類普通至多有四年夜函數,即結構函數、拷貝結構函數、析構函數和賦值函數,普通體系都邑默許。然則常常體系默許的其實不是我們所希冀的,為此我們就有需要本身發明他們。在發明之前必需懂得他們的感化和意義,做到有的放矢能力寫出有用的函數。
#include <iostream>
class CString
{
friend std::ostream & operator<<(std::ostream &, CString &);
public:
// 無參數的結構函數
CString();
// 帶參數的結構函數
CString(char *pStr);
// 拷貝結構函數
CString(const CString &sStr);
// 析構函數
~CString();
// 賦值運算符重載
CString & operator=(const CString & sStr);
private:
char *m_pContent;
};
inline CString::CString()
{
printf("NULL\n");
m_pContent = NULL;
m_pContent = new char[1];
m_pContent[0] = '\0';
}
inline CString::CString(char *pStr)
{
printf("use value Contru\n");
m_pContent = new char[strlen(pStr) + 1];
strcpy(m_pContent, pStr);
}
inline CString::CString(const CString &sStr)
{
printf("use copy Contru\n");
if(sStr.m_pContent == NULL)
m_pContent == NULL;
else
{
m_pContent = new char[strlen(sStr.m_pContent) + 1];
strcpy(m_pContent, sStr.m_pContent);
}
}
inline CString::~CString()
{
printf("use ~ \n");
if(m_pContent != NULL)
delete [] m_pContent;
}
inline CString & CString::operator = (const CString &sStr)
{
printf("use operator = \n");
if(this == &sStr)
return *this;
// 次序很主要,為了避免內存請求掉敗後,m_pContent為NULL
char *pTempStr = new char[strlen(sStr.m_pContent) + 1];
delete [] m_pContent;
m_pContent = NULL;
m_pContent = pTempStr;
strcpy(m_pContent, sStr.m_pContent);
return *this;
}
std::ostream & operator<<(std::ostream &os, CString & str)
{
os<<str.m_pContent;
return os;
}
int main()
{
CString str3; // 挪用無參數的結構函數
CString str = "My CString!"; // 聲明字符串,相當於挪用結構函數
std::cout<<str<<std::endl;
CString str2 = str; // 聲明字符串,相當於挪用結構函數
std::cout<<str2<<std::endl;
str2 = str; // 挪用重載的賦值運算符
std::cout<<str2<<std::endl;
return 0;
}
輸入:
NULL
use value Contru
My CString!
use copy Contru
My CString!
use operator =
My CString!
use ~
use ~
use ~
以上所述是小編給年夜家引見的從string類的完成看C++類的四年夜函數(面試罕見)的全體論述,願望對年夜家有所贊助,假如年夜家有任何疑問請給我留言,小編會實時答復年夜家的。在此也異常感激年夜家對網站的支撐!