C++ friend란?

Joosi_Cool·2022년 9월 25일
2

C++

목록 보기
11/20
post-thumbnail

friend란?

  • 정의
    friend 클래스란 friend로 선언된 다른 클래스의 private 및 protected 멤버에 접근할 수 있게 해줍니다.

  • 사용방법
    사용방법은 friend 키워드를 사용하여 클래스나 함수를 명시 해주는 것입니다.

예제코드

#include<iostream>
using namespace std;

class example {

private:
	int num;

public:
	example() {
		num = 1;
	}

	example(int num)
		:num{ num } {};

	void printNum() {
		cout << num << endl;
	}

	// friend 선언 => setNum()함수는 이제 example의 private, protected 변수 사용 가능
	friend void setNum(example);

};



void setNum(example x) {
	// example의 private변수인 num을 출력 가능
	cout << x.num << endl;
}

int main() {
	
	example Ex(5);
	setNum(Ex);


	return 0;

}

friend 함수의 정의 방법

  1. 외부 함수 setX()를 example 클래스에 friend로 선언

    class example{
    .....
    friend void setX(example);
    };

  2. RectManager 클래스의 setX() 멤버 함수를 example 클래스에 friend로 선언

    class example{
    .....
    friend void RectManager::setX(example);
    };

  3. RectManager 클래스의 모든 함수를 example 클래스에 friend로 선언

    class example{
    .....
    friend RectManager;
    };

+a : 참조 가능

참조자를 사용이 가능하다. 아래가 그 예시 코드이다. 아래 결과 값과 같이 참조를 통해 연산이 가능하다.

#include<iostream>
using namespace std;

class example {

private:
	int num;

public:
	example() {
		num = 1;
	}

	example(int num)
		:num{ num } {};

	void printNum() {
		cout << num << endl;
	}

	friend void setNum(example &);

};



void setNum(example &x) {
	x.num++;
	cout << x.num << endl;
}

int main() {
	
	example Ex(5);
	setNum(Ex);
	setNum(Ex);


	return 0;

}

profile
집돌이 FE개발자의 노트

0개의 댓글