C++ 字符串运算符重载详解与代码示例
下面是一个示例代码,演示了如何重载 C++ 中的字符串运算符:
#include<iostream>
#include<string>
using namespace std;
class MyString{
private:
string str;
public:
MyString() : str("") {}
MyString(string s) : str(s) {}
// 重载加号运算符
MyString operator+(const MyString& s){
return MyString(str + s.str);
}
// 重载等于运算符
bool operator==(const MyString& s){
return str == s.str;
}
// 重载小于运算符
bool operator<(const MyString& s){
return str < s.str;
}
// 重载数组下标运算符
char& operator[](int index){
return str[index];
}
// 重载流输入运算符
friend istream& operator>>(istream& is, MyString& s){
is >> s.str;
return is;
}
// 重载流输出运算符
friend ostream& operator<<(ostream& os, MyString& s){
os << s.str;
return os;
}
};
int main(){
MyString s1('hello'), s2('world'), s3;
s3 = s1 + s2;
cout << s3 << endl; // 输出 'helloworld'
cout << (s1 == s2) << endl; // 输出 '0'
cout << (s1 < s2) << endl; // 输出 '1'
s1[0] = 'H';
cout << s1 << endl; // 输出 'Hello'
cin >> s1;
cout << s1 << endl; // 输出输入的字符串
return 0;
}
在这个示例代码中,我们定义了一个名为MyString的类,它包装了一个标准字符串对象。我们重载了加号运算符、等于运算符、小于运算符、数组下标运算符、流输入运算符和流输出运算符。这些运算符的重载使得我们可以像操作基本数据类型一样操作MyString对象,使得代码更加简洁易读。
原文地址: https://www.cveoy.top/t/topic/nWu5 著作权归作者所有。请勿转载和采集!