c++定义一个字符串类String,用来存放不定长的字符串,重载运算符“==”,“<”和“>”,用于两个字符串的等于、小于和大于的比较运算。
时间: 2024-02-13 22:00:44 浏览: 30
好的,以下是一个简单的 C++ 字符串类 String 的实现,包含了您要求的重载运算符“==”,“<”和“>”:
```cpp
#include <cstring>
#include <iostream>
class String {
public:
// 构造函数
String() : m_data(nullptr), m_length(0) {}
String(const char* str) : m_length(std::strlen(str)) {
m_data = new char[m_length + 1];
std::strcpy(m_data, str);
}
String(const String& other) : m_length(other.m_length) {
m_data = new char[m_length + 1];
std::strcpy(m_data, other.m_data);
}
~String() { delete[] m_data; }
// 重载运算符
bool operator==(const String& other) const {
return std::strcmp(m_data, other.m_data) == 0;
}
bool operator<(const String& other) const {
return std::strcmp(m_data, other.m_data) < 0;
}
bool operator>(const String& other) const {
return std::strcmp(m_data, other.m_data) > 0;
}
// 获取字符串长度
size_t length() const { return m_length; }
// 获取 C 风格字符串
const char* c_str() const { return m_data; }
private:
char* m_data;
size_t m_length;
};
// 重载运算符 "!="
bool operator!=(const String& lhs, const String& rhs) {
return !(lhs == rhs);
}
// 重载运算符 "<="
bool operator<=(const String& lhs, const String& rhs) {
return !(rhs < lhs);
}
// 重载运算符 ">="
bool operator>=(const String& lhs, const String& rhs) {
return !(lhs < rhs);
}
int main() {
String s1("hello");
String s2("world");
String s3(s1);
std::cout << "s1 == s2 : " << (s1 == s2) << std::endl;
std::cout << "s1 == s3 : " << (s1 == s3) << std::endl;
std::cout << "s1 < s2 : " << (s1 < s2) << std::endl;
std::cout << "s2 > s3 : " << (s2 > s3) << std::endl;
return 0;
}
```
在这个实现中,我们使用了一个 char* 指针来存储字符串,同时记录了字符串的长度。在重载运算符时,我们使用了 C++ 标准库中的 strcmp 函数进行字符串比较。注意,我们还重载了“!=”、“<=”和“>=”运算符,这些运算符可以通过“==”和“<”运算符的组合来实现。