string類的實現(構造函數,析構函數,運算符重載)

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;
};

包括構造函數,拷貝構造函數,析構函數,算數運算符重載。


下面是測試代碼:

        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;


測試結果:

wKioL1cJuujhZEhLAAAEkgO1ngA196.png

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章