String类的编写

String类的编写

1,const & class 可以调用私有成员

2. 友元函数重载

 1 class MyString
 2 {
 3 public:
 4     MyString(char * s = NULL)
 5     {
 6         if(s != NULL)
 7         {
 8             int size = strlen(s) + 1;
 9             m_str = new char[size];
10             strcpy(m_str, s);
11         }
12         else m_str = NULL;
13     }
14     MyString(const MyString & other)
15     {
16         if(other.m_str != NULL)
17         {
18             int size = strlen(other.m_str) + 1;
19             m_str = new char[size];
20             strcpy(m_str,other.m_str);
21         }
22     }
23     MyString & operator = (const MyString & other)
24     {
25         if(m_str == other.m_str)
26             return *this;
27         delete []m_str;
28         if(other.m_str != NULL)
29         {
30             int size = strlen(other.m_str) + 1;
31             m_str = new char[size];
32             strcpy(m_str,other.m_str);
33         }
34         return *this;
35     }
36     ~MyString()
37     {
38         if(m_str != NULL)
39         delete []m_str;
40     }
41     friend ostream & operator<<(ostream &o,const MyString &str)
42     {
43         o << str.m_str ;
44         return o;
45     }
46 private:
47     char * m_str;
48 };

代码。

转载于:https://www.cnblogs.com/xubin0523/archive/2012/11/12/2766695.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值