成员函数需要有:str_copy,str_compare,str_lenth,字符串可以用‘+’实现两个字符串连接,所有的字符串都用char*或者char数组。
#include <iostream>
#include <cstring>
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() {
if (str) {
delete[] str;
}
}
// 重载赋值运算符
String& operator=(const String& s) {
if (this != &s) {
if (str) {
delete[] str;
}
int len = strlen(s.str);
str = new char[len + 1];
strcpy(str, s.str);
}
return *this;
}
// 重载 "+" 运算符
String operator+(const String& s) {
String res;
int len1 = str ? strlen(str) : 0;
int len2 = s.str ? strlen(s.str) : 0;
int len = len1 + len2;
res.str = new char[len + 1];
if (str) {
strcpy(res.str, str);
}
if (s.str) {
strcpy(res.str + len1, 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;
}
// 重载 "<" 运算符
bool operator<(const String& s) {
return strcmp(str, s.str) < 0;
}
// 重载 ">" 运算符
bool operator>(const String& s) {
return strcmp(str, s.str) > 0;
}
// 返回字符串长度
int str_length() const {
return strlen(str);
}
// 复制字符串
void str_copy(const char* s) {
if (str) {
delete[] str;
}
int len = strlen(s);
str = new char[len + 1];
strcpy(str, s);
}
// 比较字符串
int str_compare(const char* s) const {
return strcmp(str, s);
}
// 输出字符串
void print() const {
std::cout << str << std::endl;
}
};
int main() {
String s1("hello");
String s2("world");
String s3("hello");
std::cout << "s1 = ";
s1.print();
std::cout << "s2 = ";
s2.print();
std::cout << "s3 = ";
s3.print();
std::cout << "s1 == s2 ? " << (s1 == s2 ? "true" : "false") << std::endl;
std::cout << "s1 == s3 ? " << (s1 == s3 ? "true" : "false") << std::endl;
std::cout << "s1 != s2 ? " << (s1 != s2 ? "true" : "false") << std::endl;
std::cout << "s1 < s2 ? " << (s1 < s2 ? "true" : "false") << std::endl;
std::cout << "s1 > s2 ? " << (s1 > s2 ? "true" : "false") << std::endl;
String s4 = s1 + s2;
std::cout << "s1 + s2 = ";
s4.print();
s1.str_copy("world");
std::cout << "after s1.str_copy(\"world\") s1 = ";
s1.print();
std::cout << "s1.str_compare(\"world\") = " << s1.str_compare("world") << std::endl;
std::cout << "s1.str_length() = " << s1.str_length() << std::endl;
return 0;
}