完成下列的 String 类,并在主函数 main( )中测试它。 class String { public: String(const char *str = NULL); // constructor String(const String &other); // copy constructor ~ String(void); // destructor String & operate =(char *str); String & operate =(const String &other);// 重载=运算符 int operator==(String &other); // 重载==运算符 int operator==(char *str); private: char *m_data; // used for storing the string int length; };
时间: 2024-01-09 18:03:29 浏览: 73
String类的一些常用方法的测试
下面是 String 类的实现:
```cpp
#include <cstring>
class String {
public:
String(const char* str = NULL);
String(const String& other);
~String();
String& operator=(const char* str);
String& operator=(const String& other);
int operator==(String& other);
int operator==(const char* str);
private:
char* m_data;
int length;
};
String::String(const char* str) {
if (str == NULL) {
length = 0;
m_data = new char[1];
m_data[0] = '\0';
}
else {
length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
}
String::String(const String& other) {
length = other.length;
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
String::~String() {
delete[] m_data;
}
String& String::operator=(const char* str) {
if (m_data == str) {
return *this;
}
delete[] m_data;
if (str == NULL) {
length = 0;
m_data = new char[1];
m_data[0] = '\0';
}
else {
length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
return *this;
}
String& String::operator=(const String& other) {
if (m_data == other.m_data) {
return *this;
}
delete[] m_data;
length = other.length;
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
return *this;
}
int String::operator==(String& other) {
return strcmp(m_data, other.m_data) == 0;
}
int String::operator==(const char* str) {
return strcmp(m_data, str) == 0;
}
```
在主函数中可以这样测试:
```cpp
#include <iostream>
int main() {
String str1("hello");
String str2("world");
String str3(str1);
std::cout << "str1 = " << str1 << std::endl;
std::cout << "str2 = " << str2 << std::endl;
std::cout << "str3 = " << str3 << std::endl;
str2 = str1;
std::cout << "After str2 = str1, str2 = " << str2 << std::endl;
if (str1 == str2) {
std::cout << "str1 is equal to str2" << std::endl;
}
else {
std::cout << "str1 is not equal to str2" << std::endl;
}
if (str1 == "hello") {
std::cout << "str1 is equal to \"hello\"" << std::endl;
}
else {
std::cout << "str1 is not equal to \"hello\"" << std::endl;
}
return 0;
}
```
阅读全文