一个简单string类的实现

参考:http://coolshell.cn/articles/10478.html


#include <stdio.h>
#include <string.h>
#include <vector>

class my_string
{
    public:
    my_string():m_str(new char[1]) {m_str[0] = '\0';}
        
    my_string(const char* pch):m_str(new char[strlen(pch) + 1] )   { strcpy(m_str, pch); }
    
    my_string(const my_string &str):m_str(new char[ str.size() + 1 ] )  { strcpy(m_str, str.c_str());  }
    
    my_string operator=(const my_string &str)
    {
        printf("Call = fun!\n");

        delete []m_str;
        m_str = new char[ str.size() + 1 ];
        strcpy(m_str, str.c_str());
        return *this;
    }
    
    char &operator[](const int pos)
    {
        printf("Call not const [] fun\n");
        return m_str[pos];
    }
    
    const char &operator[](const int pos) const
    {
        printf("Call const [] fun\n");
        return m_str[pos];
    }
    
    char* operator&(const int pos){return &m_str[pos];}
    ~my_string(){ delete []m_str;}    
        
    unsigned int size() const {return strlen(m_str); }
    const char* c_str() const { return m_str;}

    private:
        char *m_str;



};


void foo(my_string x)
{
}
 
void bar(const my_string& x)
{
}
 
my_string baz()
{
  my_string ret("world");
  return ret;
}

my_string str1("0123456789qqqqq");
my_string str2("0123456789");

void test_referenc_ret()
{
    str2 = str1;
    
}

int main()
{
    my_string str1("0123456789qqqqq");
    printf("str1[5] is %c\n", str1[5]);   
    str1[5] = 'a';
    printf("str1[5] is %c\n", str1[5]);   
    
    const my_string str2("0123456789");
    printf("str2[5] is %c\n", str2[5]);   

    my_string str3;
    str3 = str1;
    printf("str1 is %s, str3 is %s\n", str1.c_str(), str3.c_str());   
/*
  my_string s0;
  my_string s1("hello");
  my_string s2(s0);
  my_string s3 = s1;
  s2 = s1;
 
  foo(s1);
  bar(s1);
  foo("temporary");
  bar("temporary");
  my_string s4 = baz();
 
  std::vector<my_string> svec;
  svec.push_back(s0);
  svec.push_back(s1);
  svec.push_back(baz());
  svec.push_back("good job");
  */
}





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值