#include #include using namespace std;

class str { private: char* st; // 存储字符串的数组指针 public: str(const char* a) { // 构造函数,初始化字符串 st = new char[strlen(a) + 1]; strcpy(st, a); } str& operator=(const str& a) { // 重载=运算符,实现字符串赋值 delete[] st; // 先释放原有的字符串内存 st = new char[strlen(a.st) + 1]; // 重新分配内存 strcpy(st, a.st); // 复制字符串 return *this; } void show() { // 输出字符串 cout << st << endl; } ~str() { // 析构函数,释放内存 delete[] st; } };

int main() { str s1("他"); str s2("她"); s1.show(); s2.show(); s2 = s1; s1.show(); s2.show(); system("pause"); return 0; }


原文地址: https://www.cveoy.top/t/topic/oX32 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录