64,648
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
class String{
struct Srep; //表示
Srep* rep;
public:
class Cref{ //引用char
friend class String;
String& s;
int i;
Cref(String& ss,int ii):s(ss),i(ii){}
public:
operator char() const
{
return s.read(i);
}
void operator= (char c)
{
s.write(i,c);
}
};
class Range{}; //用于异常
String(); //x = ""
String(const char*); //x = "abc"
String(const String&);//x = other_String
String& operator= (const char*);
String& operator= (const String&);
~String();
void check(int) const;
char read(int) const;
void write(int,char);
Cref operator[] (int);
char operator[] (int i) const;
int size() const;
String& operator+=(const String&);
String& opetator+=(const char*);
void show() const;
};
#include"String.h"
#include<string.h>
struct String::Srep{
char* s; //到元素的指针
int sz; //字符个数
int n; //引用计数
Srep(int nsz,const char* p)
{
n = 1;
sz = nsz;
s = new char[sz + 1];//为了结束符增加空间
strcpy(s,p);
}
~Srep()
{
delete[] s;
}
Srep* get_own_copy() //需要时克隆
{
if(n == 1) return this;
n--;
return new Srep(sz,s);
}
void assign(int nsz,const char* p)
{
if(sz != nsz){
delete[] s;
sz = nsz;
s = new char[sz + 1];
}
strcpy(s,p);
}
private:
Srep(const Srep&);
Srep& operator= (const Srep&);
};
String::String() //以空串为默认值
{
rep = new Srep(0,"");
}
String::String(const String& x) //复制构造函数
{
x.rep->n++;
rep = x.rep; //共享表示
}
String::~String()
{
if(--rep->n == 0) delete rep;
}
String& String::operator= (const String& x) //复制赋值
{
x.rep->n++; //保护,防止“st=st”
if(--rep->n == 0) delete rep;
rep = x.rep; //共享表示
return *this;
}
//伪装的复制运算以const char* 作为参数,以提供字符串文字量
String::String(const char* s)
{
rep = new Srep(strlen(s),s);
}
String& String::operator= (const char* s)
{
if(rep->n == 1)
rep->assign(strlen(s),s); //再利用Srep
else{
rep->n--;
rep = new Srep(strlen(s),s);//使用新的Srep
}
return *this;
}
void String::check(int i) const
{
if(i < 0 || rep->sz <= i)
throw Range();
}
char String::read(int i) const
{
return rep->s[i];
}
void String::write(int i,char c)
{
rep = rep->get_own_copy();
rep->s[i] = c;
}
String::Cref String::operator[] (int i)
{
check(i);
return Cref(*this,i);
}
char String::operator[] (int i) const
{
check(i);
return rep->s[i];
}
int String::size() const
{
return rep->sz;
}
void String::show()const
{
std::cout<<this->rep->s;
}