完成下列的 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 14:03:29 浏览: 202
以下是 String 类的实现以及在主函数 main() 中的测试。
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class String {
public:
String(const char *str = NULL);
String(const String& other);
~String(void);
String& operator=(char *str);
String& operator=(const String& other);
int operator==(String& other);
int operator==(char *str);
private:
char *m_data;
int length;
};
String::String(const char* str) {
if (str != NULL) {
length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
else {
length = 0;
m_data = new char[1];
*m_data = '\0';
}
}
String::String(const String& other) {
length = other.length;
m_data = new char[length + 1];
strcpy(m_data, other.m_data);
}
String::~String(void) {
delete[] m_data;
}
String& String::operator=(char *str) {
if (m_data == str) {
return *this;
}
if (str != NULL) {
length = strlen(str);
char *temp = new char[length + 1];
strcpy(temp, str);
delete[] m_data;
m_data = temp;
}
else {
length = 0;
delete[] m_data;
m_data = new char[1];
*m_data = '\0';
}
return *this;
}
String& String::operator=(const String& other) {
if (m_data == other.m_data) {
return *this;
}
length = other.length;
char *temp = new char[length + 1];
strcpy(temp, other.m_data);
delete[] m_data;
m_data = temp;
return *this;
}
int String::operator==(String& other) {
return strcmp(m_data, other.m_data) == 0;
}
int String::operator==(char *str) {
return strcmp(m_data, str) == 0;
}
int main() {
String s1("hello");
String s2(s1);
String s3("world");
String s4;
s4 = s1;
cout << s1.operator==("hello") << endl; // 1
cout << s1.operator==(s2) << endl; // 1
cout << s1.operator==(s3) << endl; // 0
cout << s1.operator==(s4) << endl; // 1
return 0;
}
```
阅读全文