9.11 Qt
思维导图:
#include <iostream> #include <cstring> using namespace std;class MyString {friend ostream& operator<<(ostream& cout, const MyString& q);friend istream& operator>>(istream& cin, MyString& q);private:char* p;public:// 无参构造函数MyString() : p(nullptr) {}// 有参构造函数:从C风格字符串构造MyString(const char* str){if (str){p = new char[strlen(str) + 1];strcpy(p, str);}else{// 处理空指针情况p = new char[1];*p = '\0';}}// 拷贝构造函数MyString(const MyString& other){if (other.p){p = new char[strlen(other.p) + 1];strcpy(p, other.p);}else{p = nullptr;}}// 析构函数~MyString(){delete[]p;p = nullptr;}// 赋值运算符重载MyString& operator=(const MyString& other){if (this != &other){delete[] p;// 复制新内容if (other.p){p = new char[strlen(other.p) + 1];strcpy(p, other.p);}else{p = nullptr;}}return *this;}// 字符串拼接赋值运算符MyString& operator+=(const MyString& q){if (!p){p = new char[strlen(q.p) + 1];strcpy(p, q.p);return *this;}// 计算新字符串长度size_t old_len = strlen(p);size_t new_len = old_len + strlen(q.p) + 1;char* new_p = new char[new_len];strcpy(new_p, p);strcat(new_p, q.p);delete[] p;p = new_p;return *this;}// 获取字符串长度int size() const{return strlen(p);}// 大于比较运算符bool operator>(const MyString& q) const{if (!p && !q.p) return false;if (!p) return false;if (!q.p) return true;return strcmp(p, q.p) > 0;} }; // 输出运算符重载 ostream& operator<<(ostream& cout, const MyString& q) {cout << q.p;return cout; }// 输入运算符重载 istream& operator>>(istream& cin, MyString& q) {char buffer[1024];cin >> buffer;delete[] q.p;// 分配新内存并复制输入内容q.p = new char[strlen(buffer) + 1];strcpy(q.p, buffer);return cin; }int main() {MyString p1;MyString p2;cout << "input p1: ";cin >> p1;cout << "input p2: ";cin >> p2;cout << "p1: " << p1 << endl;cout << "p2: " << p2 << endl;cout << "p1.len: " << p1.size() << endl;cout << "p2.len: " << p2.size() << endl;if (p1 > p2){cout << "p1 > p2" << endl;}else{cout << "p1 <= p2" << endl;}p1 += p2;cout << "p1+p2: " << p1 << endl;return 0; }