1. 程式人生 > >運算子過載 : Cstring實現

運算子過載 : Cstring實現

class Cstring 
{
public:
	Cstring(char*ptr=NULL) 
	{
		if(cptr == NULL)
		{
			cptr = new char[1];
			cptr[0] = 0;
		}
		else
		{
			cptr = new char[strlen(ptr)+1];
			strcpy(cptr,ptr);
		}
	}
	~Cstring()
	{
		delete []cptr;
		cptr =NULL;
	}
	Cstring(const Cstring &src )
	{
		//拷貝建構函式
		cptr = new char[strlen(src.cptr)+1];
		strcpy(cptr,src.cptr);
	}
	//返回的不是區域性變數就返回引用
	Cstring &operator=(const Cstring &src)
	{
		if( cptr == src.cptr)
		{
			return *this;
		}
		  delete []cptr; 

		  cptr = new char[strlen(src.cptr)+1];
		  strcpy(cptr,src.cptr);
		  return *this;
	}

	bool operator>(const Cstring &src)
	{
		return strcmp(cptr,src.cptr)>0;
	}
	bool operator<(const Cstring &src)
	{
		return strcmp(cptr,src.cptr)<0;
	}
	bool operator==(const Cstring &src)
	{
		return strcmp(cptr,src.cptr)==0;
	}
	char&operator[](int i)
	{
		return cptr[i];
	}
	char* c_str()
	{
		return cptr;
	}
	int length()
	{
		return strlen(cptr);
	}
private:
	char*cptr ;
	friend ostream& operator<<(ostream &out , const Cstring &src) ;
	friend Cstring operator+(const Cstring &src, const  Cstring &srv);
};

ostream& operator<<(ostream &out , const Cstring &src)
{
	cout<<src.cptr;
	return out;
}

Cstring operator+(const Cstring &src, const  Cstring &srv)
{
	char *p = new char[strlen(src.cptr)+strlen(srv.cptr)];
	strcpy(p,src.cptr);
	strcat(p,srv.cptr);
	Cstring tmp(p);
	return tmp;
}

int main()
{
	Cstring str1 = "abc";
	Cstring str2="bcd";
	Cstring str4 = str2;
	Cstring str3=str1+str2;
	cout<<str4<<endl;
	cout<<str3<<endl;
	system("pause");
	return 0;
}