Programming Language/C++

[C++] 16.Unmanaged Programming: Friend 키워드

coco_daddy 2024. 1. 29. 13:52

Vector의 operator<<() 연산자 만들기

friend 키워드를 사용하는 사례

// Vector.h
class Vector
{
    friend void operator<<(std::ostream& os, const Vector& rhs);
private:
    int mX;
    int mY;
};

// Vector.cpp
void operator<<(std::ostream& os, const Vector& rhs)
{
    os << rhs.mX << ", " << rhs.mY;
}
  1. 전역함수
  2. 좌항과 우항을 인자로 받음
  • Vector의 private 멤버 변수를 어떻게 읽는냐에 대한 문제가 있다.
    friend 함수를 쓰면 된다.
  • 클래스 별로 hpp 파일을 만들고 cpp에 구현을 할 텐데, 이 오버로딩 함수는 어디에 넣어야 할까?
    → Vector.cpp 파일에 구현해 놓는다. Vector와 관련이 있고, 다른 파일에 넣는다면 딱히 들어갈 곳이 없기 때문이다.

friend 키워드

클래스 정의 안에 friend 키워드를 사용할 수 있다. 다른 클래스나 함수가 해당 클래스의 private/protected 멤버에 접근할 수 있게 허용한다.

위의 함수를 friend 키워드를 통해 해결할 수 있다.

// X.h
class X
{
    friend class Y;
private:
    int mPrivateInt;
}

 

class Yprivate 멤버에 접근할 수 있게 된다.

friend 함수

// X.h
class X
{
    friend void Foo(X& x);
private:
    int mPrivateInt;
}

// GlobalFunction.cpp
void Foo(X& x)
{
    x.mPrivateInt += 10;
}

클래스뿐만 아니라 전역함수에 대해서도 멤버 변수 접근을 가능하게 할 수 있다.

연산자 오버로딩에 필요한 friend 함수

  • friend 함수는 멤버 함수가 아니다.
  • 다른 클래스의 private 멤버에 접근할 수 있다.

Vector의 operator<<() 연산자를 friend 키워드를 사용하여 만들기

class Vector
{
    friend void operator<<(std::ostream& os, const Vector& rhs);
}

void operator<<(std::ostream& os, const Vector& rhs)
{
    os << rhs.mX << ", " << rhs.mY;
}

여기서 operator<<Vector의 연산자가 아니라 전역 함수이다.

  • Vector의 private 멤버 변수를 어떻게 읽는냐에 대한 문제가 있다.
    friend 함수를 사용
void operator<<(std::ostream& os, const Vector& rhs);

std::cout << vector1 << std::endl;

→ std::cout << vector1 의 반환값이 void 이다. 따라서 void << std::endl; 에서 컴파일 에러가 난다.

반환 값을 std::ostream& 을 주고 os를 그대로 반환해주면 된다.

std::ostream& operator<<(std::ostream& os, const Vector& rhs);

std::cout << vector1 << std::endl;