#include <iostream>
#include <cstring>
using namespace std;
class myString //定义一个类
{
private:
char *str; //记录c风格的字符串,这是一个指针,指向一片动态的堆区内存空间
int size; //用来记录所存放的字符串的实际长度
public:
//无参构造用于给类对象申请空间
myString():size(10) //构造函数初始化列表
{
str=new char[size]; //构造出一个长度为10的字符串
cout<<"无参构造"<<endl;
}
//有参构造
myString(const char *s)//此处的const修饰的是值,值不可以改变,但是p的指向可以改变
{
size=strlen(s);
str=new char[size+1];
strcpy(str,s);
cout<<"有参构造"<<endl;
}
//拷贝构造
myString(const myString & other)
{
size=other.size;
str=new char[size+1]; //深度拷贝
strcpy(str,other.str);
cout<<"拷贝构造"<<endl;
}
//析构函数:在对象消亡时回收对象的内存空间以及善后工作的
~myString()
{
delete []str; //先释放之前分配的空间内存数据
str=NULL;
cout<<"析构函数"<<endl;
}
//判空函数
bool empty()
{
if(strlen(str)==0)
{
return true;
}
else
{
return false;
}
}
//size函数
int length()
{
return size;
}
//c_str函数
const char * c_str() //C++风格的字符串转换为C风格字符串需要调用成员函数:c_str()
{
return str;
}
//at函数:成员访问
char &at(int pos)
{
if(pos>=size || pos<0) //判断位置是否越界了
{
cout <<"段错误"<<endl;
}
return str[pos];
}
//运算符重载 =
myString& operator=(const myString &other)
{
strcpy(this->str, other.str);
return *this; //返回本对象
}
//[]重载
char operator[](int pos)
{
if(pos<0 || pos>size)
{
cout << "越界" << endl;
}
return str[pos];
}
//+重载
myString operator+(const myString &other)
{
strcat(this->str, other.str);
return *this;
}
//>
bool operator>(const myString &other)
{
if(this->str > other.str)
return true;
else
return false;
}
//<重载
bool operator<(const myString &other)
{
if(this->str < other.str)
return true;
else
return false;
}
//设置友元
friend ostream &operator<<(ostream &L, const myString &O);
friend istream &operator>>(istream &L, const myString &O);
};
//<<
ostream &operator<<(ostream &L, const myString &O)
{
L << O.str;
return L;
}
//>>
istream &operator>>(istream &L, const myString &O)
{
L >> O.str;
return L;
}
int main()
{
//有参构造函数
myString s1("nihao"); //赋初值,然后调用有参构造函数
cout<<"s1= "<<s1.c_str()<<endl;
//拷贝构造函数
myString s2(s1); //把s1的字符串拷贝给s2
cout<<"s2= "<<s2.c_str()<<endl;
cout<<"s2.length()="<<s2.length()<<endl; //计算s2字符串的长度
cout<<"s2.c_str()="<<s2.c_str()<<endl; //把C++风格的字符串s2转换为C风格字符串
cout<<"s2.at(2)="<<s2.at(2)<<endl; //把s2下标为2的成员显示出来
//=
myString s3;
s3 = s1;
cout<<"s3="<<s3.c_str()<<endl;
//[]
cout << "s3[1]= " << s3[1] << endl;
//+
myString s4;
s4 = s2+s3;
cout << s4.c_str() << endl;
//判断大小
if(s1>s4)
cout<<"大于"<<endl;
else if(s1<s4)
cout<<"小于"<<endl;
else
cout<<"s1=s4"<<endl;
//运算符重载<<
cout << s3 << endl;;
return 0;
}