您好,登錄后才能下訂單哦!
String類的代碼:
class String { public: String(char* str="") { _str = new char[strlen(str) + 1]; strcpy(_str, str); } String(const String& str) { _str = new char[strlen(str._str) + 1]; strcpy(_str, str._str); } ~String() { delete[] _str; } String& operator=(const String& str) { if (&str == this) return *this; delete[] _str; _str = new char[strlen(str._str) + 1]; strcpy(_str, str._str); return *this; } bool operator==(const String& str) { return strcmp(_str, str._str) == 0; } friend ostream& operator<<(ostream& o,String& str) { o << str._str; return o; } private: char* _str; };
包括構(gòu)造函數(shù),拷貝構(gòu)造函數(shù),析構(gòu)函數(shù),算數(shù)運(yùn)算符重載。
下面是測試代碼:
String s1 = "hello"; String s2 = "world"; String s3 = "o"; cout << "s1=" << s1 << endl; cout << "s2=" << s2 << endl; cout << "s3=" << s3 << endl; cout << endl; String s4(s1); String s5(s1); String s6(s1); s5 = s2; cout << "s4=" << s4 << endl; cout << "s5=" << s5 << endl; cout << (s4 == s5) << endl; cout << (s4 == s6) << endl;
測試結(jié)果:
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。