溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

string類的實現(xiàn)(構(gòu)造函數(shù),析構(gòu)函數(shù),運(yùn)算符重載)

發(fā)布時間:2020-07-31 18:55:13 來源:網(wǎng)絡(luò) 閱讀:319 作者:劉子蛋gogogo 欄目:編程語言

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é)果:

string類的實現(xiàn)(構(gòu)造函數(shù),析構(gòu)函數(shù),運(yùn)算符重載)

向AI問一下細(xì)節(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)容。

AI