时间:2021-02-19 15:20:40 | 栏目: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 ~