模拟实现string类

11 篇文章 1 订阅

直接上代码

#include<iostream>
using namespace std;
#include<string.h>
class String
{
    private:
    char *ptr;
    public:
    String(const char *s=""):ptr(new char[strlen(s) + 1])//1.为什么要初始化列表,而没有写进函数里面   
{
    strcpy(ptr, s);
}
String(String &a)                                     //2、为什么要用& ,优点在哪
{
    ptr=new char[strlen(a.ptr) + 1];
    strcpy(ptr ,a.ptr);
}
~String()
{
    if (ptr)
    {
        delete ptr;
        ptr = NULL;
    }
}
void print()
{
    cout <<ptr<<endl;
}
String & operator =(const String & a)
{
    if (this == &a)return *this;
    delete ptr;
    ptr = new char[strlen(a.ptr) + 1];
    strcpy(ptr, a.ptr);
    return *this;
}
String & operator+(const String & a)
{
    String temp;
    temp.ptr =new char [strlen(a.ptr)+strlen(ptr)+1];
    temp.ptr =strcat(ptr,a.ptr);
    // strcat(temp.ptr,a.ptr);
    return temp; 
}
char & operator[](int i)
{
    if(i<0)
    {
    cout<<"Bad subscript!"<<endl;exit(1);
    }
    return ptr[i];
}
    friend istream & operator>>(istream&is,const String & a);
    friend ostream & operator<<(ostream&is,const String & a);
};
istream & operator>>(istream & is,const String & a)
{
    is>>a.ptr;
    return is;
}


ostream & operator<<(ostream & os,const String & a)
{
    os<<a.ptr;
    return os;
}
int main()
{
    String ob;
    String ob1 ("hello");
    String ob2 ("world");
    String ob3(ob1);
    cout<<ob2[2]<<endl;
    cout<<ob<<endl<<ob1<<endl<<ob2<<endl<<ob3<<endl;
    ob2 = ob1;cout<<ob1<<"  "<<ob2;
    cout<<ob1+ob2<<endl;
    return 0;
}

1. 关于第一个问题,为什么要用成员初始化列表,其原因在于:
- 成员初始化列表写法方便、简练;尤其当需要初始化的数据成员较多时更显其优越性。
- 在C++中某些类型的成员是不允许在构造函数中用赋值语句直接赋值的,例如,对于const修饰的数据成员,或是引用类型的数据成员,是不允许用赋值语句直接赋值的,因此,只能用成员初始化列表赌气进行初始化。
2.关于为什么要用对象的引用&,而不只是对象
- 使用&可以确保传过来的参数就是对象本身,传的是一个地址,并且&并不会另外开辟内存单元,使用对象引用作为函数参数不但具有对象指针作为函数参数的优点,而且对象引用用作函数参数将是程序简单,直接。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值