模拟实现string类

来源:互联网 发布:实矩阵有实SVD分解 编辑:程序博客网 时间:2024/06/05 19:24
#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、关于第一个问题,为什么要用成员初始化列表,其原因在于:

1)、成员初始化列表写法方便、简练;尤其当需要初始化的数据成员较多时更显其优越性。

2)、在C++中某些类型的成员是不允许在构造函数中用赋值语句直接赋值的,例如,对于const修饰的数据成员,或是引用类型的数据成员,是不允许用赋值语句直接赋值的,因此,只能用成员初始化列表赌气进行初始化。

2、关于为什么要用对象的引用&,而不只是对象

         使用&可以确保传过来的参数就是对象本身,传的是一个地址,并且&并不会另外开辟内存单元,使用对象引用作为函数参数不但具有对象指针作为函数参数的优点,而且对象引用用作函数参数将是程序简单,直接。