String類的實現

class String
{
private:
	char *m_data;
public:
	String(const char *str = NULL);//默認構造函數
	String(const String& other);//拷貝構造函數
	~String();//析構函數
	String &operator=(const String&other);//重載賦值運算符
	bool operator==(const String&other);//重載equals運算符
	String operator+(const String&other);//重載連接運算符
	char &operator[](int index);//重載下標訪問運算符
	friend ostream& operator<<(ostream& out , const String& str);//重載輸出運算符
	friend istream& operator>>(istream& in , String& str);//重載輸入運算符
	size_t size()const{
		return strlen(m_data);
	}
};
String::String(const char *str)
{
	 if(NULL == str){
		 m_data = new char[1];
		 *m_data = '\0';
	 }else{
		 m_data = new char[strlen(str)+1];
		 strcpy(m_data , str);
	 }
}
String::String(const String& other)
{
	m_data = new char[strlen(other.m_data)+1];
	strcpy(m_data , other.m_data);
}
String::~String()
{
	delete []m_data;
}
String& String::operator=(const String&other)
{
	if(this != &other){
		if(NULL != m_data)
			delete []m_data;
		m_data = new char[strlen(other.m_data)+1];
		strcpy(m_data , other.m_data); 
	}
	return *this;
}
bool String::operator==(const String&other)
{
	int len1 = this->size();
	int len2 = other.size();
	return strcmp(m_data , other.m_data)?false:true;
}
String String::operator+(const String&other)
{
	int len1 = this->size();
	int len2 = other.size();
	String newStr;
	newStr.m_data = new char[len1+len2+1];
	strcpy(newStr.m_data , m_data);
	strcat(newStr.m_data,other.m_data);
	return newStr;
}
char &String::operator[](int index)
{
	assert(index>=0 && index<this->size());
	return m_data[index];
}
ostream& operator<<(ostream& out , const String& str)
{
	out<<str.m_data;
	return out;
}
istream& operator>>(istream& in , String& str)
{
	char buffer[1024];
	char c;
	int i=0;
	while((c=in.get())!='\n'){
		buffer[i++] = c;
	}
	buffer[i] = '\0';
	if(NULL != str.m_data)
		delete []str.m_data;
	str.m_data = new char[i+1];
	strcpy(str.m_data , buffer);
	return in;
}


發佈了79 篇原創文章 · 獲贊 62 · 訪問量 24萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章