实现mystring类

 #include <iostream>
 #include <string>
 #include <cstring>
 #include <cstdio>
 using namespace std;
 
 class Mystring
 {
     public:
         //无参构造函数
         Mystring()
         {
             str=nullptr;
             len=0;
             cout<<"无参构造函数"<<endl;
         }
         //有参构造函数
         Mystring(const char* s)
         {
             len=strlen(s);
             str=new char[len+1];
             strcpy(str,s);
             cout<<"有参构造函数"<<endl;                                      
         }
         //拷贝构造函数
         Mystring(Mystring &other):str(new char[other.len+1]),len(other.len)
         {
             strcpy(str,other.str);
             cout<<"深拷贝构造函数"<<endl;
         }
 
         //拷贝赋值函数
         Mystring& operator=(const Mystring &other)
         {                                                    
             if(&other!=this)
             {
                 len=other.len;
             }
             if(nullptr==str)
             {
                 str=new char(other.len+1);
             }
             strcpy(str,other.str);
             cout<<"拷贝赋值函数"<<endl;
             return *this;
         }
 
         //data()   c_str() 获取字符串首地址
         char* data()
         {
             return str;
         }
    
         //size()    length()
         int size()
         {
             return len;
                                                                
         }

         //empty()
         bool empty()
         {
             returb 0==len;   
         }

         //at() 通过下标访问string类中字符串对应的位置
         char& at(int index)
         {
             if(index>=len || index<0)
             {
                 cout<<index<<"越界了"<<endl;
                 return str[0];
             }
             return str[index];                                         
         }

         //析构函数
         ~Mystring()
         {
             if(str!=nullptr)
             {
                 delete []str;
                 str=nullptr;
             }
             cout<<"析构函数"<<endl;
         }
 
     private:
         char *str;
         int len;
 };
 
int main(int argc, const char *argv[])
{
    string s("hello");
                                               
    Mystring string1("hello");//构造函数
    Mystring string2(string1);//拷贝构造函数
    Mystring string3;//无参构造函数
    string3=string1;//拷贝赋值函数

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值