Computer Security

#6 C++ 프렌드 본문

프로그래밍/C++

#6 C++ 프렌드

쿠리 Kuri 2022. 6. 17. 18:30

캡슐화 기법중 하나인 프렌드에 대해 알아보자.

 

프렌드
C++에서는 기본적으로 멤버 변수에 접근하기 위해서 public 멤버 함수를 이용해야 한다.

다만 특정한 객체의 멤버 함수가 아닌 경우에도 private 멤버에 접근해야 할 때가 있다.

이 때 프렌드(friend) 키워드를 이용하면 특정한 객체의 모든 멤버에 접근할 수 있다.

 

프렌드 함수
프렌드(Friend) 함수는 기존의 함수 앞에 friend 키워드를 붙인 형태로 사용할 수 있다.

 

코드 예시

#include <iostream>
#include <string>
using namespace std;
class Student {
private:
int studentId;
string name;
public:
Student(int studentId, string name): studentId(studentId), name(name) { }
friend Student operator +(const Student &student, const Student &other) {
return Student(student.studentId, student.name + " & " + other.name); // friend 키워드를 이용해 이름에 접근
}
void showName() { cout << "이름: " << name << '\n'; }
};
int main(void) {
Student student(1, "고동산");
Student result = student + student;
result.showName();
system("pause");
}

결과 값


프렌드 클래스
프렌드는 멤버 함수 이외에도 프렌드 클래스(Friend Class) 형태로 사용할 수 있다.

두 클래스가 서로 밀접한 연관성이 있으며 상대방의 private 멤버에 접근해야 한다면 클래스 자체를 프렌드로 선언할 수 있다.
프렌드 클래스에서는 모든 멤버 함수가 특정 클래스의 프렌드이다.

 

프렌드 클래스: 시간 클래스 정의

코드 예시

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
class Time {
friend class Date; // Date 클래스에서 Time 클래스를 이용할 수 있음.
private:
int hour, min, sec;
public:
void setCurrentTime() {
time_t currentTime = time(NULL);
struct tm *p = localtime(&currentTime);
hour = p->tm_hour;
min = p->tm_min;
sec = p->tm_sec;
}
};

 

날짜 클래스도 정의하고, 직접 사용해보자.

코드 예시

class Date {
private:
	int year, month, day;
public:
	Date(int year, int month, int day) : year(year), month(month), day(day) { }
	void show(const Time& t) {
		cout << "지정된 날짜: " << year << "년 " << month << "월 " << day << "일" << '\n';
			cout << "현재 시간: " << t.hour << ":" << t.min << ":" << t.sec << '\n';
	}
};
int main(void) {
	Time time;
	time.setCurrentTime();
	Date date = Date(2022, 6, 17);
	date.show(time);
	system("pause");
}

 

총 코드

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

class Time {
	friend class Date; // Date 클래스에서 Time 클래스를 이용할 수 있음.
private:
	int hour, min, sec;
public:
	void setCurrentTime() {
		time_t currentTime = time(NULL);
		struct tm* p = localtime(&currentTime);
		hour = p->tm_hour;
		min = p->tm_min;
		sec = p->tm_sec;
	}
};

class Date {
private:
	int year, month, day;
public:
	Date(int year, int month, int day) : year(year), month(month), day(day) { }
	void show(const Time& t) {
		cout << "지정된 날짜: " << year << "년 " << month << "월 " << day << "일" << '\n';
			cout << "현재 시간: " << t.hour << ":" << t.min << ":" << t.sec << '\n';
	}
};
int main(void) {
	Time time;
	time.setCurrentTime();
	Date date = Date(2022, 6, 17);
	date.show(time);
	system("pause");
}

 

결과 값

 

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

#8 C++ 다형성 기법 1  (0) 2022.06.19
#7 정적멤버,상수멤버  (0) 2022.06.18
#5 C++ 오버로딩  (0) 2022.06.16
#4 C++ 클래스 상속  (0) 2022.06.15
#3 C++ 생성자와 소멸자  (0) 2022.06.14
Comments