从string类的实现看C++类的四大函数 [写的很好]

很久之前参加过一次面试,记得当时面试官问过我一个很基础的代码题:实现string类的四大基本函数!

一个C++类一般至少有四大函数,即构造函数、拷贝构造函数、析构函数和赋值函数,一般系统都会默认。但是往往系统默认的并不是我们所期望的,为此我们就有必要自己创造他们。在创造之前必须了解他们的作用和意义,做到有的放矢才能写出有效的函数。

 1 #include <iostream>
 2 
 3 class CString
 4 {
 5     friend std::ostream & operator<<(std::ostream &, CString &);
 6     public:
 7         // 无参数的构造函数
 8         CString();
 9         // 带参数的构造函数
10         CString(char *pStr);
11         // 拷贝构造函数
12         CString(const CString &sStr);
13         // 析构函数
14         ~CString();
15         // 赋值运算符重载
16         CString & operator=(const CString & sStr);
17     
18     private:
19         char *m_pContent;
20 
21 };
22 
23 inline CString::CString()
24 {
25     printf("NULL\n");
26     m_pContent = NULL;
27     m_pContent = new char[1];
28     m_pContent[0] = '\0';
29 }
30 
31 inline CString::CString(char *pStr)
32 {
33     printf("use value Contru\n");
34     m_pContent = new char[strlen(pStr) + 1];
35     strcpy(m_pContent, pStr);
36 }
37 
38 inline CString::CString(const CString &sStr)
39 {
40     printf("use copy Contru\n");
41     if(sStr.m_pContent == NULL)
42         m_pContent == NULL;
43     else
44     {
45         m_pContent = new char[strlen(sStr.m_pContent) + 1];
46         strcpy(m_pContent, sStr.m_pContent);
47     }
48 }
49 
50 inline CString::~CString()
51 {
52     printf("use ~ \n");
53     if(m_pContent != NULL)
54         delete [] m_pContent;
55 }
56 
57 inline CString & CString::operator = (const CString &sStr)
58 {
59     printf("use operator = \n");
60     if(this == &sStr)
61         return *this;
62     // www.cdtarena.com顺序很重要,为了防止内存申请失败后,m_pContent为NULL
63     char *pTempStr = new char[strlen(sStr.m_pContent) + 1];
64     delete [] m_pContent;
65     m_pContent = NULL;
66     m_pContent = pTempStr;
67     strcpy(m_pContent, sStr.m_pContent);
68     return *this;
69 }
70 
71 std::ostream & operator<<(std::ostream &os, CString & str)
72 {
73     os<<str.m_pContent;
74     return os;
75 }
76 
77 
78 int main()
79 {
80     CString str3;  // 调用无参数的构造函数
81     CString str = "My CString!";  // 声明字符串,相当于调用构造函数
82     std::cout<<str<<std::endl;
83     CString str2 = str;  // 声明字符串,相当于调用构造函数
84     std::cout<<str2<<std::endl;
85     str2 = str;   // 调用重载的赋值运算符
86     std::cout<<str2<<std::endl;
87     return 0;
88 }
NULL
use value Contru
My CString!
use copy Contru
My CString!
use operator =
My CString!
use ~
use ~
use ~

转载于:https://www.cnblogs.com/robbychan/archive/2013/05/01/3786679.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值