1、^ ~ 重载
2、myString
#include <iostream>
#include <cstring>
using namespace std;
using namespace std;
class myString
{
private:
char *str; //记录c风格的字符串
int size; //记录字符串的实际长度
public:
//无参构造
myString() : str(new char[1]), size(0)
{
str[0] = '\0';
//cout<<"无参构造"<<endl;
}
//有参构造
myString(const char* s)
{
size = strlen(s);
str = new char[size + 1];
strcpy(str, s);
//cout<<"有参构造"<<endl;
}
myString(string s1)
{
size = s1.size();
str = new char[size + 1];
strcpy(str, s1.c_str());
// cout<<"有参构造"<<endl;
}
//拷贝构造
myString(const myString &other)
{
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
//cout<<"拷贝构造"<<endl;
}
//拷贝赋值函数
myString& operator=(const myString &other)
{
if (this != &other) {
delete[] str;
size = other.size;
str = new char[size + 1];
strcpy(str, other.str);
//cout<<"拷贝赋值"<<endl;
}
return *this;
}
//析构函数
~myString()
{
delete[] str;
//cout<<"析构"<<endl;
}
//判空函数
bool empty()
{
return size==0;
}
//size函数
void mysize()
{
cout<<"size = "<<size<<endl;
}
//c_str函数
char* c_str()
{
return str;
}
//at函数
char &at(int pos)
{
if (pos < 0 || pos >= size) {
cout<<"位置不合法"<<endl;
}
return str[pos];
}
//运算符重载
//+重载
friend myString operator+(const myString s1,const myString s2);
//左移/右移运算符重载
friend ostream &operator<<(ostream &out,myString s1);
friend istream &operator>>(istream &in,myString &s1);
//>、<、==、!=重载
friend bool operator>(const myString s1,const myString s2);
friend bool operator<(const myString s1,const myString s2);
friend bool operator==(const myString s1,const myString s2);
friend bool operator!=(const myString s1,const myString s2);
};
myString operator+(const myString s1,const myString s2)
{
myString temp;
temp.size = s1.size+s2.size;
temp.str=strcpy(temp.str,strcat(s1.str,s2.str));
return temp;
}
//左移运算符重载
ostream &operator<<(ostream &out,myString s1)
{
out<< s1.str <<" "<<s1.size;
return cout;
}
//右移运算符重载
istream &operator>>(istream &in,myString &s1)
{
string s;
in>>s;
s1.size = s.size();
strcpy(s1.str, s.c_str());
return cin;
}
bool operator>(const myString s1,const myString s2)
{
string s3 =s1.str;
string s4 =s2.str;
return s3>s4;
}
bool operator<(const myString s1,const myString s2)
{
string s3 =s1.str;
string s4 =s2.str;
return s3<s4;
}
bool operator==(const myString s1,const myString s2)
{
string s3 =s1.str;
string s4 =s2.str;
return s3==s4;
}
bool operator!=(const myString s1,const myString s2)
{
string s3 =s1.str;
string s4 =s2.str;
return s3!=s4;
}
int main()
{
// myString s1("hello");
// myString s2 = s1;
// myString s3;
// cout<<s1.at(4)<<endl;
// cout<<s1.c_str()<<endl;
// cout<<s2.at(4)<<endl;
// cout<<s2.c_str()<<endl;
// cout<<s2.empty()<<endl;
// s2.mysize();
myString s1("hello");
myString s2("world");
myString s3=s1+s2;
cout<<s3<<endl;
cout<<(s2>s3)<<endl;
cout<<(s2<s3)<<endl;
cout<<(s2==s3)<<endl;
cout<<(s2!=s3)<<endl;
myString s4;
cin>>s4;
cout<<s4<<endl;
return 0;
}
3、思维导图