1.重载下列运算符
2.代码
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Mystring {
public:
Mystring() { // 无参构造函数
len = 0;
str = nullptr;
}
Mystring(const char *s) { // 有参构造函数
len = strlen(s);
str = new char[len + 1]; // +1 给 '\0' 留空间
strcpy(str, s);
}
~Mystring() { // 析构函数
if (str != nullptr) {
delete[] str;
}
}
// 深拷贝构造函数
Mystring(const Mystring &other) : len(other.len), str(new char[other.len + 1]) {
strcpy(str, other.str);
}
// 拷贝赋值函数
Mystring &operator=(const Mystring &other) {
if (this != &other) {
if(str != nullptr){
delete[] str; // 释放旧内存
str = nullptr;
}
len = other.len;
str = new char[len + 1];
strcpy(str, other.str);
}
return *this;
}
const char* data() const { // 返回内容的字符数组形式
return str;
}
size_t size() const { // 返回当前字符串拥有的字符数
return len;
}
bool empty() const { // 判断字符串是否为空
return len == 0;
}
char& at(size_t index) {
if (index >= len) {
throw out_of_range("下标数值超出范围");
}
return str[index];
}
//连接两个字符串对象(运算符+重载)
Mystring operator+(const Mystring& R){
Mystring s;
s.len = len + R.len;
s.str = new char[len+1];
strcpy(s.str , str);
strcat(s.str , R.str);
return s;
}
//operator!=重载
bool operator!=(const Mystring& R){
return strcmp(str,R.str) != 0;
}
//operator==重载
bool operator==(const Mystring& R){
return strcmp(str,R.str) == 0;
}
//operator<重载
bool operator<(const Mystring& R){
return strcmp(str,R.str) < 0;
}
//operator<=重载
bool operator<=(const Mystring& R){
return strcmp(str,R.str) <= 0;
}
//operator>重载
bool operator>(const Mystring& R){
return strcmp(str,R.str) > 0;
}
//operator>=重载
bool operator>=(const Mystring& R){
return strcmp(str,R.str) >= 0;
}
friend ostream& operator<<(ostream& L, const Mystring& R);
friend istream& operator>>(istream& L, Mystring& R);
private:
size_t len; // 使用 size_t 避免负数问题
char *str;
};
//operator<<重载
ostream& operator<<(ostream& L, const Mystring& R){
L<<R.str;
return L;
}
//operator>>重载
istream& operator>>(istream& L, Mystring& R){
L>>R.str;
return L;
}
int main(int argc, const char *argv[]) {
Mystring s1("hello"); // 调用有参构造函数初始化
cout << s1.at(0) << endl; // 输出第一个字符 'h'
cout << s1.data() << endl; // 输出整个字符串 "hello"
cout << s1.empty() << endl; // 字符串不为空,返回 0
Mystring s2(" hahaha"); // 空字符串
cout <<s2.empty() << endl; // 空字符串,返回
cout <<"s2="<<s2.data()<< endl;
Mystring s3(s1); //调用深拷贝构造函数
cout<<"s3="<<s3.data()<<endl;
Mystring s4("hello world");
s1 = s4; //调用拷贝赋值函数
cout<<"s4="<<s4.data()<<endl;
Mystring s5;
s5 = s1 + s2;
cout << "s5=" << s5.data() << endl;
bool res = (s1!=s2);
cout<<"res="<<res<<endl;
cout<<s5<<endl;
cout<<(s5 >= s4)<<endl;
return 0;
}