C++記憶體分配和管理
/* String.h */
#ifndef STRING_H_
#define STRING_H_
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 <iostream>
#include <cstring>
#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';//為了方便觀察結果,特留此行程式碼。
delete [] str;
}
ostream & operator<<(ostream & os, const String & st)
{
os << st.str;
return os;
}
/*test_right.cpp*/
#include <iostream>
#include <stdlib.h>
#include "String.h"
using namespace std;
int main()
{
String temp("天極網");
cout<<temp<<'"n';
system("PAUSE");
return 0;
}