重写String类

2015/07/26 C和C++基础
#include <iostream>
using namespace std;

class String{
public:
	String(const char *str=NULL){           //有参构造函数
		if(str==NULL){
			s=new char[1];
			s[0]='\0';
		}else{
			s=new char[strlen(str)+1];
			strcpy(s,str);
		}
	}
	String(const String &str){         //拷贝构造函数
		int len=strlen(str.s);
		s=new char[len+1];
		strcpy(s,str.s);
	}
	~String(){                         //析构函数
		delete []s;
	}
	int length(){                      //求长度
		int len=strlen(s);
		return len;
	}
	String& operator=(const String &str){    //重载=符号 String对象
		if(&str==this) return *this;
		delete []s;
		s=new char[strlen(str.s)+1];
		strcpy(s,str.s);
		return *this;
	}

	String& operator=(const char* str){      //重载=符号 char*
		delete []s;
		s=new char[strlen(str)+1];
		strcpy(s,str);
		return *this;
	}
	
	String operator+(const String &str){     //重载+符号
		String tmp;
		delete []tmp.s;
		tmp.s=new char[strlen(this->s)+strlen(str.s)+1];
		tmp.s[0]='\0';
		strcat(tmp.s,this->s);
		strcat(tmp.s,str.s);
		return tmp;
	}
	friend ostream& operator<<(ostream &,const String &);  //重载输出流
private:
	char *s;
};

ostream& operator<<(ostream &output,const String &str){
	output<<str.s;
	return output;
}

int main(){
	String s("hello world");
	cout<<s<<" "<<s.length()<<endl;
	String s1("nimei");
	s=s1;
	cout<<s<<" "<<s.length()<<endl;
	s="ni daye de!!!";
	cout<<s<<" "<<s.length()<<endl;

	String s3="hehe";
	String s4="HEHE";
	s=s3+s4;
	cout<<s<<" "<<s.length()<<endl;
	system("pause");
}

Search

    Post Directory