從string類的實現看C++類的四大函數(面試常見)
朋友面試的一道面試題,分享給大家,面試官經常會問到的,實現string類的四大基本函數必掌握。
一個C++類一般至少有四大函數,即構造函數、拷貝構造函數、析構函數和賦值函數,一般系統(tǒng)都會默認。但是往往系統(tǒng)默認的并不是我們所期望的,為此我們就有必要自己創(chuàng)造他們。在創(chuàng)造之前必須了解他們的作用和意義,做到有的放矢才能寫出有效的函數。
#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++類的四大函數(面試常見)的全部敘述,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對我們網站的支持!
上一篇:簡單實現C++復數計算器
欄 目:C語言
本文標題:從string類的實現看C++類的四大函數(面試常見)
本文地址:http://www.jygsgssxh.com/a1/Cyuyan/2232.html
您可能感興趣的文章
- 01-10深入理解鏈表的各類操作詳解
- 01-10用C++實現DBSCAN聚類算法
- 01-10深入探討C++父類子類中虛函數的應用
- 01-10基于C語言string函數的詳解
- 01-10用C++實現strcpy(),返回一個char*類型的深入分析
- 01-10深入理解c++中char*與wchar_t*與string以及wstring之間的相互轉換
- 01-10利用ace的ACE_Task等類實現線程池的方法詳解
- 01-10深入理解:Java是類型安全的語言,而C++是非類型安全的語言
- 01-10c++友元函數與友元類的深入解析
- 01-10c++中拷貝構造函數的參數類型必須是引用


閱讀排行
本欄相關
- 04-02c語言函數調用后清空內存 c語言調用
- 04-02func函數+在C語言 func函數在c語言中
- 04-02c語言的正則匹配函數 c語言正則表達
- 04-02c語言用函數寫分段 用c語言表示分段
- 04-02c語言中對數函數的表達式 c語言中對
- 04-02c語言編寫函數冒泡排序 c語言冒泡排
- 04-02c語言沒有round函數 round c語言
- 04-02c語言分段函數怎么求 用c語言求分段
- 04-02C語言中怎么打出三角函數 c語言中怎
- 04-02c語言調用函數求fibo C語言調用函數求
隨機閱讀
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 04-02jquery與jsp,用jquery
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-10C#中split用法實例總結
- 01-11ajax實現頁面的局部加載
- 08-05dedecms(織夢)副欄目數量限制代碼修改
- 08-05織夢dedecms什么時候用欄目交叉功能?


