上一篇文章简单介绍了malloc/free和new/delete的区别,当然,我建议大家多用new/delete;
下面上一段代码让大家更好的来理解这个应用
///String.h/// #ifndef STRING_H_ #define STRING_H_ #include <iostream> using namespace std; class String { private: char * str; //存储数据 int len; //字符串长度 public: String(const char * s); //构造函数 String(); // 默认构造函数 ~String(); // 析构函数 friend ostream & operator<<(ostream & os,const String& st); }; #endif
String.cpp #include "stdafx.h" #include <string> #include <iostream> #include "String.h" using namespace std; String::String(const char *s) { len=strlen(s); str=new char[len+1]; strcpy(str,s); } String::String() { len=0; str=new char[len+1]; str[0]='"0'; } String::~String() { cout<<"将完成删除操作;"<<str<<'"n'<<endl; delete []str; cout<<str<<endl; } ostream &operator <<(ostream &os,const String &st) { os<<st.str; return os; }// testString.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include "String.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { String temp("wangchenglin 我爱你"); cout<<temp<<endl; //system("PAUSE"); return 0; }
程序运行的结果:
很诡异的是,我delete操作,为什么依然还是垃圾呢?