string類的簡易實現(C++)

1.示例代碼
#include<bits/stdc++.h>

using namespace std;

class String
{
public:
	String():_size(0), _str(NULL){ }
	String(char *str);
	String(const String &des);
	String & operator=(const String &des);
	static int getStrNum(){return _strnum;}
	friend strSwap(String &first, String &second); 
	friend ostream& operator<<(ostream &os, const String &src);
	~String();
private:
	int _size;
	char* _str;	
	static int _strnum;	
};
int String::_strnum = 0;

String::String(char *str)    //構造函數 
{
	cout<<"String::String(char *str)"<<endl;
	_size = strlen(str); 
	_str = new char[_size+1];
	strcpy(_str, str);
	_strnum++;
}
String::String(const String &des)    //拷貝構造函數 
{
	cout<<"String::String(const String &des)"<<endl;
	_size = des._size; 
	_str = new char[_size+1];
	strcpy(_str, des._str);
	_strnum++;
}

strSwap(String &first, String &second)
{
	swap(first._size, second._size); 
    swap(first._str, second._str);
}

//沒有考慮異常安全 
//String & String::operator=(const String &des)    //等號運算符重載
//{
//	cout<<"String & String::operator=(const String &des)"<<endl;
//	if(this == &des)
//	{
//		return *this;
//	}
//	
//	if(NULL != _str)
//	{
//		delete[] _str;
//		_strnum--;
//	}
//	
//	_size = des._size; 
//	_str = new char[_size+1];
//	strcpy(_str, des._str);
//	_strnum++;
//}

//考慮異常安全 
String & String::operator=(const String &des)    //等號運算符重載
{
	cout<<"String & String::operator=(const String &des)"<<endl;
	_strnum--;
	String tmp(des);
	strSwap(*this, tmp);
	return *this;
} 

ostream& operator<<(ostream &os, const String &src)
{
	os<<"字符串:"<<src._str<<endl;
	os<<"長度:"<<src._size<<""; 
}

String::~String()    //析構函數 
{
	cout<<"String::~String()"<<endl;
	delete[] _str;
	_str = NULL; 
}

int main()
{
	char* p = "Hello World!";
	String str1(p);
	cout<<str1<<endl;
	cout<<"字符串個數:"<<String::getStrNum()<<endl;
	cout<<"*****************************************"<<endl;
	String str2("zhangling");
	cout<<str2<<endl;
	cout<<"字符串個數:"<<String::getStrNum()<<endl;
	cout<<"*****************************************"<<endl;
	str2 = str1;
	cout<<str2<<endl;
	cout<<"字符串個數:"<<String::getStrNum()<<endl;
	cout<<"*****************************************"<<endl;
	String str3 = str1;
	cout<<str1<<endl;
	cout<<"字符串個數:"<<String::getStrNum()<<endl;
	cout<<"*****************************************"<<endl;
	return 0;
}
2.運行結果

在這裏插入圖片描述

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