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;
}
'Programming > C C++' 카테고리의 다른 글
Garbage Collection & Reference Counting (0) | 2020.10.22 |
---|---|
Lambda를 써야하는 이유와 사용 방법 (0) | 2020.10.16 |
prefix increment operator vs. postfix increment operator (0) | 2020.10.12 |
C++ 정적 바인딩과 동적 바인딩 (0) | 2020.09.29 |