国庆day2
编程题
题目1:自定义字符串类实现
题目描述:
实现一个简单的自定义字符串类MyString,要求:
- 1】支持构造函数、拷贝构造函数、赋值运算符
- 2】实现基本的字符串操作:长度、拼接、比较
- 3】实现对MyString 对象的输入、输出
- 4】正确处理内存管理
#include <iostream>using namespace std;class Mystring
{
private:string *str1;
public:Mystring():str1(nullptr){cout<<"调用了无参构造函数"<<endl;}Mystring(string str1):str1(new string(str1)){cout<<"调用了有参构造函数"<<endl;}Mystring(const Mystring &other):str1(new string(*(other.str1))){cout<<"调用了拷贝构造函数"<<endl;}Mystring &operator=(const Mystring &other){if(this!=&other){delete str1;str1=new string(*(other.str1));cout<<"调用了拷贝赋值函数"<<endl;}return *this;}void show(){cout<<"字符串为:"<<*str1<<endl;}~Mystring(){cout<<"调用了析构函数"<<endl;}// 1.My_strlen函数int My_strlen(){if (str1 == nullptr)return 0;return str1->size();}// 2.My_strcat 函数Mystring My_strcat(const Mystring &other){string temp;if (str1 != nullptr)temp += *str1;if (other.str1 != nullptr)temp += *(other.str1);return Mystring(temp);}// 3.My_strcmp函数int My_strcmp(const Mystring &other){if (str1 == nullptr && other.str1 == nullptr)return 0;if (str1 == nullptr)return -1;if (other.str1 == nullptr)return 1;if (*str1 < *(other.str1))return -1;else if (*str1 > *(other.str1))return 1;elsereturn 0;}// 4. 输入输出运算符重载(友元函数)friend ostream &operator<<(ostream &os, const Mystring &obj);friend istream &operator>>(istream &is, Mystring &obj);
};// 输出运算符重载实现
ostream &operator<<(ostream &os, const Mystring &obj)
{if (obj.str1 != nullptr)os << *(obj.str1);return os;
}// 输入运算符重载实现
istream &operator>>(istream &is, Mystring &obj)
{string temp;is >> temp;if (obj.str1 != nullptr){delete obj.str1;obj.str1 = nullptr;}obj.str1 = new string(temp);return is;
}int main()
{cout<<"请输入字符串"<<endl;string str;cin>>str;Mystring str1=str;string key;while(1){cout<<"提示:strlen"<<endl;cout<<"提示:strcat"<<endl;cout<<"提示:strcmp"<<endl;cout<<"请输入你想要的操作"<<endl;cin>>key;if(key=="strlen"){cout<<"触发了长度计算"<<endl;cout<<"字符串长度是:"<<str1.My_strlen()<<endl; // 调用长度函数continue;}else if(key=="strcat"){cout<<"触发了拼接功能,请输入要拼接的字符串:"<<endl;Mystring str2;cin>>str2; // 调用输入运算符Mystring str3 = str1.My_strcat(str2); // 调用拼接函数cout<<"拼接后的字符串:"<<str3<<endl; // 调用输出运算符continue;}else if(key=="strcmp"){cout<<"触发了比较功能,请输入要比较的字符串:"<<endl;Mystring str2;cin>>str2; // 调用输入运算符int res = str1.My_strcmp(str2); // 调用比较函数if(res < 0)cout<<"原字符串小于要比较的字符串"<<endl;else if(res > 0)cout<<"原字符串大于要比较的字符串"<<endl;elsecout<<"两个字符串相等"<<endl;continue;}else if(key=="0"){cout<<"谢谢使用,再见"<<endl;return 0;}else{cout<<"输入不合法,请重新输入"<<endl;continue;}}str1.show();return 0;
}
运行结果
牛客网刷题