#include <iostream>
#include<cstring>
using namespace std;
//定义mystring类
class mystring
{
private :
char *str;//记录c风格字符串
int size;//记录字符串长度
public :
//无参构造
mystring():size(10)
{
str=new char[size];//构造一个长度为10的字符串
strcpy(str,"");
}
//有参构造
mystring(const char *s)
{
size=strlen(s);
str=new char [size+1];
strcpy(str,s);
}
//拷贝构造
mystring(mystring & other):str(new char(*(other.str))),size(other.size)//new char [other.size]
{
strcpy(str,other.str);
cout<<"构造拷贝"<<endl;
}
//析构函数
~ mystring()
{
delete str;//deldete [] str
cout<<" stu::析构函数"<<endl;
}
//判空函数
bool empty()
{
if(0==strlen(str))
{
return true;
}
else
return false;
}
//size函数
int length()
{
return size;
}
//c_str函数
const char *c_str()
{
return str;
}
//at函数
char & at(int pos)
{
if(pos<0||pos>=size)
{
cout<<"输入不合法"<<endl;
}
return str[pos];
}
//+ 运算符重载
const mystring operator +(const mystring & other)const
{
mystring temp;
temp.size=this->size-1;
temp.str=new char[this->size+other.size-1];//两个字符串结尾\0
strcpy(temp.str,this->str);
strcat(temp.str,other.str);
return temp;
}
//= 运算符重载
mystring & operator = (const mystring & other)
{
if(this!=&other)
{
delete this->str;
this->str=new char[other.size];
strcpy(this->str,other.str);
}
return *this;
}
//[]运算符重载
char operator [](int pos)
{
if(pos>size||pos<0)
{
cout<<"输入不合法"<<endl;
}
return *(str+pos);
}
//==运算符重载
bool operator==(const mystring & other)const
{
if(0==strcmp(this->str,other.str))
return true;
else
return false;
}
//>运算符重载
bool operator >(const mystring & other)const
{
if(stricmp(this->str,other.str)>0)
{
return true;
}
else
return false;
}
//<运算符重载
bool operator <(const mystring & other)const
{
if(stricmp(this->str,other.str)<0)
{
return true;
}
else
return false;
}
friend ostream &operator <<(ostream &cout,const mystring &other);
friend istream &operator >>(istream &cin, mystring &other);
};
//输出运算符<<
ostream &operator <<(ostream &cout,const mystring &other)
{
cout<<other.str<<endl;
cout<<other.size<<endl;
return cout;
}
//输入运算符>>
istream &operator >>(istream &cin, mystring &other)
{
string str;
cout<<"请输入一个字符串"<<endl;
cin>>str;
delete other.str;
memset(other.str,0,other.size);
strcpy(other.str,str.c_str());
other.size=str.size();
return cin;
}
int main()
{
//有参构造
mystring str("666888 ni hao");
cout<<"有参构造:"<<str.c_str()<<endl;
//拷贝构造
mystring str1(str);
cout<<"拷贝 str1="<<str.c_str()<<endl;
//析构函数
//判空函数
cout<<"判空函数:"<<str1.empty()<<endl;
//size函数
cout<<"size函数 size="<<str.length()<<endl;
//c_str函数
cout<<"c_str函数 str="<<str.c_str()<<endl;
//at函数
cout<<"at函数 str[1]="<<str.at(1)<<endl;
//+ 运算符重载
cout<<"+ 运算符重载"<<str+str1<<endl;
//[]运算符重载
cout<<"[]运算符重载"<<str[1]<<endl;
//==运算符重载
cout<<"=运算符重载"<<(str==str1)<<endl;
//>运算符重载
cout<<">运算符重载"<<(str>str1)<<endl;
//<运算符重载
cout<<"<运算符重载"<<(str<str1)<<endl;
//输出运算符<<
cout<<"输出运算符<<"<<str<<endl;
//输入运算符>>
cin>>str1;
cout<<"输入运算符"<<str1<<endl;
return 0;
}
输出结果为: