#include <iostream>
#include<cstring>
using namespace std;
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 &m)
{
size=strlen(m.str);
str=new char[size+1];
strcpy(str,m.str);
cout<<"拷贝构造函数"<<endl;
}
//析构函数
~myString()
{
delete [] str;
cout<<"析构函数"<<endl;
}
//判空函数
int myempty()
{
if(!strcmp(str,""))
return 0;
return true;
}
//size函数
int mysize()
{
return strlen(str);
}
//c_str函数
char* &myc_str()
{
return str;
}
//at函数
char &at(int pos)
{
int l=strlen(str);
if(pos>l)
{
cout<<"pos超出范围"<<endl;
}
return str[pos];
}
//拷贝赋值函数
myString & operator = (const myString &other)
{
cout<<"拷贝赋值函数"<<endl;
delete[]this->str;
size=strlen(other.str);
str=new char[size+1];
strcpy(this->str ,other.str);
return *this;
}
//[]
char &operator[](int index)
{
return this->str[index];
}
//+号;
const char* operator +(const myString &other)const
{
myString temp;
delete[] temp;
temp.size=strlen(str)+strlen(other.str);
temp.str=new[size+1];
strcpy(temp,str);
strcat(temp,other.str);
return temp;
}
//<、==、>实现strcmp
bool operator ==(const myString &other)const
{
return (strcmp(this->str,other.str)==0)?true:false;
}
bool operator >(const myString &other)const
{
return (strcmp(this->str,other.str)>0)?true:false;
}
bool operator <(const myString &other)const
{
return strcmp(this->str,other.str)<0?true:false;
}
//cin,cout
friend ostream &operator<<(ostream &l,const myString &dst);
friend istream &operator>>(istream &l, myString &dst);
};
ostream & operator <<(ostream &l,const myString &dst)
{
l<<dst.str;
return l;
};
istream &operator>>(istream &l, myString &dst)
{
l>>dst.str;
return l;
};
int main()
{
myString s1("1234");
cout<<"s1= "<<s1.myc_str()<<endl;
myString s2=s1;
cout<<"s2= "<<s2.myc_str()<<endl;
cout<<"length= "<<s2.mysize()<<endl;
if(!s2.myempty())
cout<<"字符串为空"<<endl;
else
cout<<"字符串不为空"<<endl;
cout<<"s2[1]="<<s2.at(1)<<endl;
myString s3 ;
s3=s1;
cout<<"s3="<<s3<<endl;
myString s4;
cout<<"请输入s4"<<endl;
cin>>s4;
cout<<"s4="<<s4<<endl;
s1=s2+s3;
cout<<"s2+s3="<<s1<<endl;
if(s4>s3)
cout<<"s4>s3"<<endl;
}
c++作业
于 2023-04-21 20:58:44 首次发布