手動實現動態字符串管理,包含:
>>、<<、==、>、<、=class String {
public:
String(const char* str = NULL); // 普通構造
String(const String& other); // 拷貝構造
~String(); // 析構
String& operator=(const String& other); // 賦值重載
friend bool operator==(const String&, const String&);
friend bool operator>(const String&, const String&);
friend bool operator<(const String&, const String&);
friend ostream& operator<<(ostream&, const String&);
friend istream& operator>>(istream&, String&);
private:
char* m_data;
};
String::String(const char* str) {
if (str == NULL) {
m_data = new char[1];
*m_data = '\0';
} else {
int len = strlen(str);
m_data = new char[len + 1];
strcpy(m_data, str);
}
}
String::~String() { delete[] m_data; }
String::String(const String& other) {
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
}
String& String::operator=(const String& other) {
if (this == &other) return *this; // 自賦值檢查
delete[] m_data;
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
return *this;
}
ostream& operator<<(ostream& os, const String& s) {
os << s.m_data;
return os;
}
istream& operator>>(istream& is, String& s) {
char buf[256];
is >> buf;
int len = strlen(buf);
delete[] s.m_data;
s.m_data = new char[len + 1];
strcpy(s.m_data, buf);
return is;
}
bool operator==(const String& s1, const String& s2) {
int len1 = strlen(s1.m_data), len2 = strlen(s2.m_data);
if (len1 != len2) return false;
for (int i = 0; i < len1; ++i)
if (s1.m_data[i] != s2.m_data[i]) return false;
return true;
}
bool operator>(const String& s1, const String& s2) {
int len = min(strlen(s1.m_data), strlen(s2.m_data));
for (int i = 0; i < len; ++i) {
if (s1.m_data[i] > s2.m_data[i]) return true;
if (s1.m_data[i] < s2.m_data[i]) return false;
}
return strlen(s1.m_data) > strlen(s2.m_data);
}
bool operator<(const String& s1, const String& s2) {
int len = min(strlen(s1.m_data), strlen(s2.m_data));
for (int i = 0; i < len; ++i) {
if (s1.m_data[i] < s2.m_data[i]) return true;
if (s1.m_data[i] > s2.m_data[i]) return false;
}
return strlen(s1.m_data) < strlen(s2.m_data);
}
int main() {
String s; cin >> s; cout << "s: " << s << endl;
String a = "1234";
String b(a); // 拷貝構造
String c; c = a; // 賦值
cout << "a: " << a << " b: " << b << " c: " << c << endl;
if (s > b) cout << "s > b";
else if (s < b) cout << "s < b";
else cout << "s == b";
cout << endl;
return 0;
}
strcpyif (this == &other) return *this;const String&m_data此實現覆蓋了 C++ 類設計的核心:資源管理(RAII)、拷貝控制、運算符重載、流式輸入輸出,是掌握 C++ 底層機制的優秀練習。