用c++写1、定义一个字符串类,重载的运算符包括: =、+、+=、>、<、>=、<=、==、!=。其中,除=、+=运算符用成员函数定义外、其余的运算符要求用友元方式定义。
时间: 2024-11-15 09:34:49 浏览: 45
在C++中,你可以创建一个自定义的字符串类`MyString`,并重载一些常见的运算符。这里是一个简单的示例,展示如何实现你所描述的操作:
```cpp
#include <iostream>
#include <string>
class MyString {
private:
std::string str;
public:
// 构造函数和复制构造函数
MyString(const std::string& s) : str(s) {}
MyString(const MyString& other) : str(other.str) {}
// 运算符=
MyString& operator=(const MyString& other) {
if (this != &other)
str = other.str;
return *this;
}
// 运算符+
MyString operator+(const MyString& other) const {
return MyString(str + other.str);
}
MyString& operator+=(const MyString& other) {
str += other.str;
return *this;
}
// 其他比较运算符(用友元函数定义)
friend bool operator>(const MyString& a, const MyString& b) { return a.str > b.str; }
friend bool operator<(const MyString& a, const MyString& b) { return a.str < b.str; }
friend bool operator>=(const MyString& a, const MyString& b) { return !(a < b); }
friend bool operator<=(const MyString& a, const MyString& b) { return !(a > b); }
friend bool operator==(const MyString& a, const MyString& b) { return a.str == b.str; }
friend bool operator!=(const MyString& a, const MyString& b) { return a.str != b.str; }
};
int main() {
MyString str1("Hello");
MyString str2("World");
str1 = str2; // 使用 =
str1 += " C++"; // 使用 +=
std::cout << str1 << ">" << str2 << "\n"; // 输出:Hello C++>World
return 0;
}
```
在这个例子中,`>`、`<`、`>=`、`<=` 和 `==`、`!=` 运算符都被声明为朋友函数,它们可以在`MyString`类的对象上调用,并处理字符串之间的比较。
阅读全文
相关推荐



















