컴공 일기18
게시글 주소: https://orbi.kr/00056672884
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
using namespace std;
class Cstring {
private:
char* m_string;
public:
Cstring() { SetName(NULL); }
explicit Cstring(const char* p_string) {
this-> m_string = NULL;
SetName(p_string);
}
Cstring(const Cstring& rhs) {
this->m_string = NULL;
SetName(rhs.m_string);
}
Cstring* SetName(const char* p_string) {
if (m_string != NULL) delete[] p_string;
if (p_string == NULL) m_string = NULL;
else {
int size = strlen(p_string) + 1;
m_string = new char[size];
strcpy(m_string, p_string);
}
return this;
}
~Cstring() {
delete[] m_string;
}
friend std::ostream& operator <<(std::ostream& out, Cstring p) {
out << p.m_string;
return out;
}
};
int main() {
Cstring a("오르비");
Cstring b("컴공주");
cout << a <<' '<< b << endl;
return 0;
}
이 코드를 실행하면 다음과 같은 결과가 나온답니다 :D
이 예제는 문자열 붙이는 프로그램인데 굳이 "주접"을 떨기 위해서 C++ 스타일로 구현해봤습니다.
일단 이걸 만약 C++로 구현한다면 멤버 포인터 변수를 메모리 leak이 나오지 않도록 정교하게 동적할당을 해주는 것, 출력 연산자 오버로딩. 이 두 가지가 중심입니다. 덤으로 출력 연산자가 실행될 때, 복사 생성이 일어나기 때문에 memory leak를 막으려면 복사생성자 만들어주고, 그 안에서도 deep copy가 일어나도록 만들어야 합니다.
연산자 오버로딩과 생성자 함수의 원리와 호출 구조를 아주 잘 알고 있어야, 에러를 안 띄우는 문항이 되겠네용..!
0 XDK (+0)
유익한 글을 읽었다면 작성자에게 XDK를 선물하세요.
-
좋아요 1 답글 달기 신고
-
좋아요 0 답글 달기 신고