본문 바로가기
Programming/C C++

operator Overloading

by Eisen Sophie 2021. 1. 7.

CMy_String.

class CMy_String {

public:
	CMy_String();
	CMy_String(const char* str);
	CMy_String(const CMy_String& other);
	CMy_String& operator=(const CMy_String& rhs);
	~CMy_String();

	CMy_String operator+(const CMy_String& str);
	CMy_String operator+(char* str);
	friend CMy_String operator+ (const char* lhs, CMy_String& rhs);

	CMy_String& operator+= (const CMy_String& str);
	CMy_String& operator+= (char* str);
	
	bool operator==(const CMy_String& str);
	bool operator==(char* str);
	friend bool operator==(const char* lhs, CMy_String& rhs);

	friend ostream& operator<<(ostream& os, const CMy_String& str);

private:
	char* mP;
	int mLen;
};

 

main.

	CMy_String str1("Hello");
	CMy_String str2("World");

	CMy_String str3 = str1 + str2; 		// 1

	cout << str3 << endl;

	CMy_String str4 = str1 + "RightHand"; 	 // 2
	CMy_String str5 = "LeftHand" + str1; 	`// 3

	cout << str4 << endl; 			// 4
	cout << str5 << endl;

 

 

1. CMy_String str3 = str1 + str2;

CMy_String CMy_String::operator+(const CMy_String& str) {
	
	char* newP = new char[this->mLen + str.mLen + 1];
	
	strcpy(newP, this->mP);
	strcat(newP, str.mP);
	
	CMy_String newStr(newP);

	return newStr;
}

 

 

2. CMy_String str4 = str1 + "RightHand";

CMy_String::CMy_String(const char* str) {
	mLen = strlen(str);
	mP = new char[mLen + 1];
	strcpy(mP, str);
}

 

 

3. CMy_String str5 = "LeftHand" + str1; 

CMy_String operator+ (const char* lhs, CMy_String& rhs) {
	
	char* newMp = new char[strlen(lhs) + rhs.mLen + 1];

	strcpy(newMp, lhs);
	strcat(newMp, rhs.mP);

	CMy_String newStr(newMp);
	return newStr;
}

 

5. cout << str4 << endl;

ostream& operator<<(ostream& os, const CMy_String& str) {
	if (str.mP == nullptr) {
		return os;
	}

	os << str.mP;

	return os;
}