天天看点

c++学习-oop-重载赋值操作符

/*
	Date: 12/03/21 14:20
	Description: 重载赋值操作符
	赋值操作符
		==	+=	-=
		*=	/=	%=
		&=	|=	^=
		<<=	>>= 
	赋值操作符必须返回对*this的引用 
*/
#include<iostream>
#include<cstring>
using namespace std;

class String
{
public:
	String(char const *chars = "");
	
	String &operator=(String const &); 
	String &operator=(char const *);
	String &operator=(char);
	
	void print();
private:
	char *ptrChars;	
};

String::String(char const *chars)
{
	chars = chars ? chars :"";
	ptrChars = new char[strlen(chars)+1];
	strcpy(ptrChars,chars);
}

String &String::operator=(String const &str)
{
	if(strlen(ptrChars)!=strlen(str.ptrChars))
	{
		char *ptrHold = new char[strlen(str.ptrChars)+1];
		delete[] ptrChars;
		ptrChars = ptrHold;
	}
	strcpy(ptrChars,str.ptrChars);
	return *this;
}

String &String::operator=(char const *rhs)
{
	if(strlen(ptrChars)!=strlen(rhs))
	{
		char *ptrHold = new char[strlen(rhs)+1];
		delete[] ptrChars;
		ptrChars = ptrHold;
	}
	strcpy(ptrChars,rhs);
	return *this;
}

String &String::operator=(char rhs)
{
	if(!(strlen(ptrChars)==2 && *ptrChars==rhs))
	{
		char *ptrHold = new char[2];
		delete[] ptrChars;
		ptrChars = ptrHold;
		*ptrHold =rhs;
	}
	return *this;
}

void String::print()
{
	cout<<ptrChars<<endl;
}

int main()
{
	String s("hello");
	String s2("Dog");
	s.print();
	
	s=s2;
	s.print();
	s2.print();
	
	char const *s3 = "Cat";
	
	s=s3;
	s.print();
	
	char s4 = 'K';
	s=s4;
	s.print();
	return 0;
}


           

继续阅读