话不多说,直接撸码,其中原理相信很容易看懂!!!
#include<iostream>
using namespace std;
class string1
{
public:
string1();//默认构造函数
string1(int n,char c);//普通构造函数
string1(const char* source);//普通构造函数
string1(const string1& s);//复制构造函数
string1& operator =(char* s);//重载=,实现字符串的赋值
string1& operator = (const string1& s);//重载=,实现对象赋值
~string1();
char& operator[](int i);//重载[],实现数组运算
const char& operator[](int i)const;//重载[],实现数组运算(对象为常量)
string1& operator +=(const string1& s);//与字符相加
string1& operator +=(const char* s);//与对象相加
friend ostream& operator <<(ostream& out,string1& s);//实现输出流
friend istream& operator >>(istream& in,string1& s);//实现输入流
friend bool operator <(const string1& left,const string1& right);
friend bool operator >(const string1& left,const string1& right);
friend bool operator ==(const string1& left,const string1& right);
friend bool operator !=(const string1& left,const string1& right);
char* getData();
private:
int size;
char *data;
};
string1::string1()
{
data = new char[1];
size = 0;
*data = '\0';
}
string1::string1(int n,char c)
{
data = new char[n+1];
size = n;
char* temp = data;
while(n--)
{
*temp++ = c; //*temp = c;temp++;
}
*temp = '\0';
}
string1::string1(const char* source)
{
if(source == NULL)
{
data = new char[1];
*data = '\0';
size = 0;
}
else
{
size = strlen(source);
data = new char[size+1];
strcpy(data,source);
}
}
string1::string1(const string1 &s)
{
data = new char[s.size+1];
strcpy(data,s.data);
size = s.size;
}
string1& string1:: operator=(char* s)
{
if(s != NULL)
{
delete []data;
}
size = strlen(s);
data = new char[size+1];
strcpy(data,s);
return *this;
}
string1::~string1()
{
if(data != NULL)
{
delete []data;
data = NULL;
size = 0;
}
}
char& string1::operator [](int i)
{
return data[i];
}
const char& string1::operator[] (int i)const
{
return data[i];
}
string1& string1::operator+=(const string1& s)
{
int len = size+s.size+1;
char* temp = data;
data = new char[len];
size = len-1;
strcpy(data,temp);
strcat(data,s.data);
delete []data;
return *this;
}
string1::length()
{
return size;
}
ostream& operator <<(ostream &out,string1& s)
{
for(int i=0;i<s.length();i++)
{
out<<s[i]<<" ";
}
return out;
}
istream& operator >>(istream &in,string1 &s)
{
char p[50];
in.getline(p,50);
s = p;
return in;
}
bool operator < (const string1& left,const string1& right)
{
int i=0;
while(left[i]==right[i] && left[i]!=0 && right[i]!= 0)
{
i++;
}
return left[i]-right[i] < 0?true:false;
}