C++函数重载运算符重载

#include <iostream>

using namespace std;

class String
{
public:
	String();//默认构造函数
	String(int n,char c);//普通构造函数
	String(const char * sourse);//普通构造函数
	String(const String& s);//复制构造函数
	String & operator=(char *s);//重载=
	String & operator=(const String &s);//
	~String();//
	char &  operator[](int i);//
	String & operator +=(const String & s);//

	friend ostream &  operator<<(ostream &out,String &s);//
	friend istream &  operator>>(istream &in,String &s);//
	friend bool operator==(const String &left,const String &right);//
	friend bool operator> (const String &left,const String &right);//
	friend bool operator< (const String &left,const String &right);//
	friend bool operator!=(const String &left,const String &right);//
	char* getData();
	
private:
	int size;
	char * data;

};

String::String()
{
	data=new char[1];
	*data='\0';
	size=0;
}
String::String(int n,char c)
{
	data=new char[n+1];
	size=n;
	char*temp=data;
	while (n--)
	{
		*temp++=c;
	}
	*temp='\0';
}
String::String(const char * sourse)
{
	if (sourse==NULL)
	{
		data=new char[1];
		size=0;
		*data='\0';
	}
	else
	{
		size=strlen(sourse);
		data=new char[size+1];
		strcpy(data,sourse);
	}
}
String::String(const String& s)
{
	data=new char[strlen(s.data)+1];
	size=s.size;
	strcpy(data,s.data);
}
String & String::operator=(char *s)
{
	if (data!=NULL)
	{
		delete [] data;
	}
	size=strlen(s);
	strcpy(data,s);
	return *this;
}
String & String::operator=(const String &s)
{
   if (this==&s)
   {
	   return *this;
   }
   if (data!=NULL)
   {
	   delete[] data;
   }
   size=s.size;
   data=new char[size+1];
   strcpy(data,s.data);
   return *this;
}
String::~String()
{
	if (data!=NULL)
	{
		delete [] data;
		data=NULL;
		size=0;
	}
}
char & String::operator[](int i)
{
	return data[i];
}
String & String::operator+=(const String&s)
{
   return *this;
}

char * String::getData()
{
	return data;
}


void main()
{

}

你可能感兴趣的:(C++函数重载运算符重载)