1. 程式人生 > >CString的簡單實現

CString的簡單實現

注意事項:

1、注意為結尾符‘\0’申請一個位元組的空間;

2、在拷貝建構函式和賦值函式中,注意使用深拷貝,而不是淺拷貝;

3、過載輸入、輸出運算子;

#include<iostream>
#include<iomanip>
using namespace std;
 
class CString{
	friend ostream& operator<<(ostream& os, CString& str);
	friend istream& operator>>(istream& is, CString& str);
private:
	int iLen;
	char* lpszBuff;
public:
	CString(char* buff = ""){
		cout << "CString建構函式" << endl;
		iLen = strlen(buff);
		lpszBuff = new char[iLen+1];
		strcpy(lpszBuff, buff);
	}
	CString(const CString& other){
		cout << "CString拷貝建構函式" << endl;
		iLen = strlen(other.lpszBuff);
		lpszBuff = new char[iLen+1];
		strcpy(lpszBuff, other.lpszBuff);
	}
	CString& operator=(CString& other){
		if(this != &other){//防止自我賦值
			cout << "CString賦值函式" << endl;
			if(lpszBuff != NULL){
				delete lpszBuff; lpszBuff = NULL;
			}
			iLen = strlen(other.lpszBuff);
			lpszBuff = new char[iLen+1];
			strcpy(lpszBuff, other.lpszBuff);
		}
		return *this;
	}
	~CString(){
		cout << "CString解構函式" << endl;
		if(lpszBuff != NULL){
			delete lpszBuff; lpszBuff = NULL;
		}
	}
	char* C_str(){return lpszBuff;}
};
ostream& operator<<(ostream& os, CString& str){os << str.C_str(); return os;}
istream& operator>>(istream& is, CString& str){is >> str.C_str(); return is;}
 
 
void main()
{
	CString str1("Hello"); cout << "str1 : " << str1 << endl << endl;
	CString str2(str1); cout << "str2 : " << str2 << endl << endl;
	CString str3; str3 = str2; cout << "str3 : " << str3 << endl << endl;
}