请问这里的析构函数应该怎么写?
这里的析构函数应该怎么写?用来释放new过的内存程序代码:
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string.h> #include <string> using namespace std; class str { public: str(char *name); void print(str &str); int Size(str &str); static void exchange(str &str1, str &str2); static void Connect(str &str1, str &str2); ~str(); protected: char *name; int size = 0; }; str::str(char *name) { this->name = new char[strlen(name) + 1]; this->name = name; this->size = strlen(name) + 1; } void str::print(str &str) { for (int i = 0; i < str.size; i++) { cout << name[i]; } cout << endl; } int str::Size(str &str) { return str.size; } void str::exchange(str &str1, str &str2) { if (str1.Size(str1) < str2.Size(str2)) { str1.name = new char[str2.Size(str2) - 1]; memset(str1.name, 0, str2.Size(str2) - 1); strcpy(str1.name, str2.name); str1.size = str2.Size(str2) - 1; } str1.name = str2.name; } void str::Connect(str &str1, str &str2) { char *str3 = new char[(str1.Size(str1) + str2.Size(str2)) - 1]; memset(str3, 0, (str1.Size(str1) + str2.Size(str2)) - 1); strcat(str3, str1.name); strcat(str3, str2.name); str1.name = new char[(str1.Size(str1) + str2.Size(str2)) - 1]; memset(str1.name, 0, (str1.Size(str1) + str2.Size(str2)) - 1); str1.name = str3; str1.size = (str1.Size(str1) + str2.Size(str2)) - 1; } str::~str() { cout << "析构函数" << endl; } int main() { str mystr = "I LOVE YOU"; cout << "对象大小:" << mystr.Size(mystr) << endl; cout << "对象为:"; mystr.print(mystr); cout << endl; str mystr1 = "I hate you"; str mystr2 = "I miss you123"; cout << "新对象1为:"; mystr1.print(mystr1); cout << "新对象2为:"; mystr2.print(mystr2); cout << "对象复制操作" << endl; str::exchange(mystr1, mystr2); cout << "复制后对象1为:"; mystr1.print(mystr1); cout << "复制后对象2为:"; mystr2.print(mystr2); str mystr3 = "I hate you"; str mystr4 = "I miss you"; cout << "连接操作:"; str::Connect(mystr3, mystr4); mystr3.print(mystr3); system("pause"); return 0; }