#include <bits/stdc++.h> using namespace std; class String { public: String(const char* str = NULL){// 普通构造函数 cout << "普通构造函数被调用" << endl; if (str == NULL) { data = new char[1]; *data = '\0'; } else { int len = strlen(str); data = new char[len + 1]; for (int i = 0;i < len;i++) data[i] = str[i]; data[len] = '\0'; } } String(const String &other) {// 拷贝构造函数 cout << "拷贝构造函数被调用" << endl; int len = strlen(other.data); data = new char[len + 1]; for (int i = 0;i < len;i++) data[i] = other.data[i]; data[len] = '\0'; } ~String() { //析构函数 cout << "析构函数被调用" << endl; delete[]data; // 释放内存 data = NULL; // 置空指针 } String& operator = (const String &other) { //赋值构造函数 cout << "赋值构造函数被调用" << endl; if (this == &other) { return *this; } delete []data; int len = strlen(other.data); data = new char[len + 1]; for (int i = 0;i < len;i++) data[i] = other.data[i]; data[len] = '\0'; return *this; } void show() { cout << data << endl; } private: char* data; }; int main() { { String s("hello"); s.show(); String ss = String(s); //拷贝构造函数调用 ss.show(); String sss = s; //赋值 sss.show(); } system("pause"); return 0; }
标签:String,代码,析构,拷贝,构造函数,赋值 From: https://www.cnblogs.com/yzqiang/p/17685185.html