1、在類中可以訪問private成員包括兩層含義:可以訪問this指標的private成員;可以訪問同類物件的private成員。
2、這裡的string可以認為是個資源管理類,內部有個char指標,在堆上分配物件,而且對於string應該是深複製,不是複製指標,而是要複製指標指向的內容。
string類的定義(標頭檔案):
1#ifndef string_h_
2#define string_h_
3class
string4;
13#endif
string類的實現(cpp檔案):
1 #include "string.h
"2 #include 3 string::string(const
char*src)410
else
1115}16
17 string::string(const string&rhs)
1822
23 string& string::operator=(const string&rhs)
2429
delete_data;
30 _data = new
char[strlen(rhs._data)+1
];31
strcpy(_data,rhs._data);
32return *this;33
}3435 string::~string()
36
上面的string實現,使用了new char在堆上分配記憶體,當然也可以使用malloc,需要注意的是,這種情況下,要使用free釋放記憶體。而且,要注意的是,new和delete是關鍵字,而malloc和free是方法。
1 #include "string.h
"2 #include 3 string::string(const
char*src)410
else
1115}16
17 string::string(const string&rhs)
1822
23 string& string::operator=(const string&rhs)
2429
free(_data);
30 _data = (char*)malloc(strlen(rhs._data)+1
);31
strcpy(_data,rhs._data);
32return *this;33
}3435 string::~string()
36
string類的實現
參考c primer.string類的實現,清翔兔 06,jan.includeusing namespace std class string string void private char m data inline string string const char str inline st...
String類的實現
學習資料結構寫了乙個string的類,貼出來求指教 ifndef string h h define string h h include include include define defaultsize 128 class string maxsize為傳入引數的string string c...
string類的實現
include using namespace std class string public string const char str 0 普通建構函式 string const string other 拷貝建構函式 string void 析構函式 string operator const...