반응형

클래스 템플릿안에 friend 함수를 선언하는 방법

  • friend 함수 선언시에 함수 자체를 템플릿 모양으로 선언

  • friend 관계: N:N

#include <iostream>
using namespace std;

template<typename T>
class Point
{
    T x, y;
public:
    Point(T a = { 0 }, T b = { 0 }) : x(a), y(b) {}
    template<typename U>
    friend ostream& operator<<(ostream& os, const Point<U>& p);
};

template<typename T>
ostream& operator<<(ostream& os, const Point<T>& p)
{
    return os << p.x << ", " << p.y;
}


int main()
{
    Point<int> p(1, 2);
    cout << p << endl;

    Point<double> p2(1.2, 2.3);
    cout << p2 << endl;
}

 

  • friend 함수를 일반 함수로 구현하고 구현부를 클래스 템플릿 내부에 포함

  • friend 관계: 1:1

#include <iostream>
using namespace std;

template<typename T>
class Point
{
    T x, y;
public:
    Point(T a = { 0 }, T b = { 0 }) : x(a), y(b) {}
    friend ostream& operator<<(ostream& os, const Point<T>& p)
    {
        return os << p.x << ", " << p.y;
    }
};


int main()
{
    Point<int> p(1, 2);
    cout << p << endl;

    Point<double> p2(1.2, 2.3);
    cout << p2 << endl;
}
반응형

반응형

friend와 같은 명사를 사용할때는 듣는이를 위해 숫자와 소유자를 표현해주는 것이 좋다.

 

1. 친구

  • I will meet a friend. // 친구 1명 만날거야.
  • I will meet my friends. // 친구을 만날거야.

Tip.

  • I will meet a friend of mine. // 내 친구들중 1명을 만날거야.
  • I will wash my hair. // 나는 머리를 감을거야.
  • I will do my homework. // 나 숙제 할거야.
  • I will wash my hands. // 나 손 씻을거야.
반응형

반응형

생성자와 연산자 재정의를 이용한 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