#include <iostream>
#include <cstring>
using namespace std;
class mystring;
void null(mystring &s);
void size(mystring &s);
class mystring
{
private:
char *str;
int size;
public:
//无参构造
mystring():size(10)
{
str = new char[size];
strcpy(str,"");
}
//有参构造
mystring(const char *s)
{
size = strlen(s);
str = new char[size+1];
strcpy(str,s);
cout<<"有参构造"<<endl;
}
//拷贝构造
mystring(const mystring &other):str(new char(*other.str)),size(other.size)
{
cout<<"拷贝构造函数"<<endl;
}
//析构函数
~mystring()
{
cout<<"析构函数"<<endl;
}
//拷贝赋值函数
mystring & operator=(const mystring &other)
{
if(this!=&other)
{
this->size = other.size;
if(this->str != NULL)
{
delete this->str;
}
this->str = new char(*other.str);
}
cout<<"拷贝赋值函数"<<endl;
return *this;
}
//判空函数
friend void null(mystring &s);
//size函数
friend void size(mystring &s);
//c_str函数
void c_str(mystring &s)
{
cout<<"str="<<s.str<<endl;
}
//at函数
char &at(int pos);
//加号运算符重载
const mystring operator+(const mystring &R)const
{
mystring c;
c.str=strcat(str,R.str);
c.size=this->size + R.size;
return c;
}
//加等于运算符重载
mystring & operator+=(const mystring &R)
{
strcat(this->str,R.str);
this->size+=R.size;
return *this;
}
//关系运算符重载(>)
bool operator>(const mystring &other)const
{
if(strcmp(str,other.str)>0)
{
return true;
}
return false;
}
//中括号运算符重载
char & operator[](int i)
{
if(i >= 0 && i< size)
{
return this->str[i];
}
else
{
cout<<"数组越界"<<endl;
}
}
};
void null(mystring &s)
{
if(s.size==0)
{
cout<<"空字符串"<<endl;
}
cout<<"不是空字符串"<<endl;
}
void size(mystring &s)
{
cout<<"size="<<s.size<<endl;
}
int main()
{
mystring s("new");
null(s);
size(s);
s.c_str(s);
mystring s1("hello");
mystring s2=s1+s;
size(s2);
s2.c_str(s2);
mystring s3("world");
s3+=s2;
size(s3);
s3.c_str(s3);
if(s3>s1)
{
cout<<"s3>s1"<<endl;
}else
{
cout<<"s3<=s1"<<endl;
}
cout<<s3[6]<<endl;
return 0;
}
day40
最新推荐文章于 2024-10-04 22:43:57 发布