#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 &others)
{
size=others.size;
str = new char[size+1];
strcpy(str,others.str);
}
//析构函数
~myString()
{
delete [] str;
str=nullptr;
}
//判空函数
bool empty()
{
if(strlen(str) == 0)
return true;
else
return false;
}
//size函数
int my_size()
{
return strlen(str);
}
//c_str函数
int my_c_str()
{
return strlen(str);
}
//at函数
char at(int pos)
{
if(pos<0 || pos>=size)
return 'f';
else
return str[pos];
}
void show()const
{
cout<<this->str<<endl;
}
void show()
{
cout<<this->str<<endl;
}
//[]重载
char operator[](int n)
{
if(n<0||n>=this->size)
return '#';
else
{
return str[n];
}
}
//+号重载
const myString &operator+(const myString &other)
{
strcat(this->str,other.str);
return *this;
}
//>号重载
bool operator>(const myString &other)const
{
if( strcmp(this->str,other.str)>0)
return true;
else
return false;
}
//设置友元
friend myString & operator>>(istream &l,myString &o);
};
//全局函数重载>>
myString & operator>>(istream &l,myString &o)
{
l>>o.str;
return o;
}
int main()
{
myString s1("qwert");
s1.show();
myString s2(s1);
s2.show();
cout<<s2.my_c_str()<<endl;
cout<<s2.at(3)<<endl;
myString s3("12345");
cout<<"----"<<s3[2]<<"----"<<endl;
(s1+s3).show();
if(s1>s2)
cout<<"s1>s2"<<endl;
cin>>s1;
s1.show();
return 0;
}
c++运算符重载
最新推荐文章于 2024-07-11 22:03:57 发布