반응형

생성자와 연산자 재정의를 이용한 String 클래스 만들기

class String
{
    char* buff; // 문자열 버퍼
    int size; // 문자열 사이즈
public:
    String(const char* s) // 생성자
    {
        size = strlen(s);
        buff = new char[size + 1];
        strcpy(buff, s);
    }
    ~String() { delete[] buff;}

    String(const String& s) : size(s.size) // 복사 생성자(여기선 깊은 복사)
    {
        buff = new char[size + 1];
        strcpy(buff, s.buff);
    }

    String& operator=(const String& s) // 대입 연산자 재정의
    {
        // 자신과의 대입 조사
        if (&s == this)
            return *this;

        size = s.size;

        delete[] buff; // 기존 메모리 해지
        buff = new char[size + 1]; // 대입받는 문자열 사이즈로 메모리 동적 할당
        strcpy(buff, s.buff);

        return *this;
    }

    friend std::ostream& operator<<(std::ostream& os, const String& s); // 멤버 외부 접근용 friend 선언
};

std::ostream& operator<<(std::ostream& os, const String& s)
{
    os << s.buff;
    return os; 
}

int main()
{
    String s1 = "apple"; // 복사 생성자
    String s2 = "banana"; // 복사 생성자

    s1 = s2; // 대입 연산자 지원
    s1 = s1; // 자신에 대한 대입 연산자 지원

    std::cout << s1 << std::endl; // cout 출력 지원
}
반응형

'프로그래밍 언어 > C++' 카테고리의 다른 글

C++ STL 컨테이너(Container)  (0) 2019.05.11
C++ STL(Standard Template Library)  (0) 2019.05.11
C++ 대입 연산자(assignment)  (0) 2019.05.10
C++ 스마트 포인터(Smart Pointer)  (0) 2019.05.10
C++ 증감 연산자(++, --)  (0) 2019.05.10

+ Recent posts