728x90
반응형
2023.02.21 최초 작성
클래스가 친구로 인정한 함수나 클래스에 friend를 붙이면 접근제한자의 영향을 받지 않고 내부 데이터에 접근이 가능해진다.
하지만 friend를 남발한다면 캡슐화가 어려워지므로 주의가 필요하다.
friend는 편리하지만 다른 클래스의 private에 직접 접근하는 것은 보안상 좋지 않아 권장하지 않는다. 필요하면 클래스를 상속받는 구조로 만들어 쓰고 외부에서 public 메서드를 통해 접근하여 내부에서 private에 접근하는 것이 좋다.
#include <iostream>
using namespace std;
class School {
private:
char* name;
char* tel;
friend class Student;
public:
School(char* name, char* tel){
this->name = name;
this->tel = tel;
}
};
class Student {
private:
char* name;
int kor;
int eng;
int math;
public:
Student(char* name, int kor, int eng, int math)
:name(name), kor(kor), eng(eng), math(math){}
void printSchool(School s) {
cout << "학교정보" << endl;
cout << s.name << endl;
cout << s.tel << endl;
}
friend void printStudent(Student s);
};
void printStudent(Student s) {
cout << "학생정보" << endl;
cout << s.name << endl;
cout << s.kor << endl;
cout << s.eng << endl;
cout << s.math << endl;
}
int main() {
char name[]("Kim");
Student s1(name, 100, 90, 80);
printStudent(s1);
char scname[]("abc");
char sctel[]("02-1234-5678");
School sc1(scname, sctel);
s1.printSchool(sc1);
return EXIT_SUCCESS;
}
[실행 결과]
학생정보
Kim
100
90
80
학교정보
abc
02-1234-5678
728x90
반응형
728x90
반응형
'프로그래밍 > C++' 카테고리의 다른 글
상속 (0) | 2023.02.23 |
---|---|
연산자 중복 (0) | 2023.02.21 |
static 수명이 길다 (0) | 2023.02.21 |
구조체도 클래스이다. (0) | 2023.02.20 |
생성자 오버로딩 (중복사용) (0) | 2023.02.20 |