從string類的實現(xiàn)看C++類的四大函數(shù)(面試常見)
朋友面試的一道面試題,分享給大家,面試官經(jīng)常會問到的,實現(xiàn)string類的四大基本函數(shù)必掌握。
一個C++類一般至少有四大函數(shù),即構(gòu)造函數(shù)、拷貝構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù),一般系統(tǒng)都會默認(rèn)。但是往往系統(tǒng)默認(rèn)的并不是我們所期望的,為此我們就有必要自己創(chuàng)造他們。在創(chuàng)造之前必須了解他們的作用和意義,做到有的放矢才能寫出有效的函數(shù)。
#include <iostream>
class CString
{
friend std::ostream & operator<<(std::ostream &, CString &);
public:
// 無參數(shù)的構(gòu)造函數(shù)
CString();
// 帶參數(shù)的構(gòu)造函數(shù)
CString(char *pStr);
// 拷貝構(gòu)造函數(shù)
CString(const CString &sStr);
// 析構(gòu)函數(shù)
~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;
// 順序很重要,為了防止內(nèi)存申請失敗后,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; // 調(diào)用無參數(shù)的構(gòu)造函數(shù)
CString str = "My CString!"; // 聲明字符串,相當(dāng)于調(diào)用構(gòu)造函數(shù)
std::cout<<str<<std::endl;
CString str2 = str; // 聲明字符串,相當(dāng)于調(diào)用構(gòu)造函數(shù)
std::cout<<str2<<std::endl;
str2 = str; // 調(diào)用重載的賦值運算符
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類的實現(xiàn)看C++類的四大函數(shù)(面試常見)的全部敘述,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
- 詳解C++中String類模擬實現(xiàn)以及深拷貝淺拷貝
- 自己模擬寫C++中的String類型實例講解
- 詳解C++的String類的字符串分割實現(xiàn)
- C++實現(xiàn)String類實例代碼
- C++中將string類型轉(zhuǎn)化為int類型
- 詳解C++中實現(xiàn)繼承string類的MyString類的步驟
- 探究C++中string類的實現(xiàn)原理以及擴展使用
- C++中的string類的用法小結(jié)
- 分享C++面試中string類的一種正確寫法
- 利用C++實現(xiàn)從std::string類型到bool型的轉(zhuǎn)換
- c++中string類成員函數(shù)c_str()的用法
- 代碼分析c++中string類
相關(guān)文章
C語言的isatty函數(shù)和ttyname函數(shù)以及sendmsg函數(shù)用法
這篇文章主要介紹了C語言的isatty函數(shù)和ttyname函數(shù)以及sendmsg函數(shù)用法,是C語言入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09

