设计字符串类(String),定义各种构造函数并实现以下运算符重载: 1重载+(连接) 2重载==(相等)和<(小于) 3重载[]
时间: 2024-06-01 20:11:37 浏览: 6
class String {
private:
char* str;
public:
String() {
str = nullptr;
}
String(const char* s) {
int len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
String(const String& s) {
int len = strlen(s.str);
str = new char[len + 1];
strcpy(str, s.str);
}
~String() {
delete str;
}
String operator+(const String& s) {
String res;
int len1 = strlen(str);
int len2 = strlen(s.str);
res.str = new char[len1 + len2 + 1];
strcpy(res.str, str);
strcat(res.str, s.str);
return res;
}
bool operator==(const String& s) {
return strcmp(str, s.str) == 0;
}
bool operator<(const String& s) {
return strcmp(str, s.str) < 0;
}
char& operator[](int i) {
return str[i];
}
};