Test class declares Change() as a friend function and it accesses the private member variable 'a'.
아래 코드에서 Test 클래스는 Change라는 friend 함수를 선언 하고 멤버 변수 a에 접근한다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; class Test { private: int a; public: Test() { a = 0; } ~Test() { } void Show() { cout << "a: " << a << endl; } friend void Change(Test& t, int c); }; void Change(Test& t, int c) { t.a = c; } int main(int argc, char* argv[]) { Test t; t.Show(); Change(t, 10); t.Show(); return 0; } | cs |
How to set default arguments in a friend function?
friend 함수 Change에 디폴트 매개 변수를 설정하고 싶다면 어떻게 해야 할까?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; class Test { private: int a; public: Test() { a = 0; } ~Test() { } void Show() { cout << "a: " << a << endl; } friend void Change(Test& t, int c = 100); }; void Change(Test& t, int c) { t.a = c; } int main(int argc, char* argv[]) { Test t; t.Show(); Change(t, 10); t.Show(); return 0; } | cs |
Setting default arguments in the friend function declaration will cause an error message like below.
위 코드와 같이 friend 선언부에 디폴트 매개 변수를 설정 하면 별 문제 없이 빌드는 되지만 아래와 같은 메세지가 나타나게 된다.
friend declaration cannot add default arguments to previous declaration

Try to set default arguments in the function definition.
아래와 같이 함수 정의부에 디폴트 매개 변수를 설정 하면 에러 메세지가 나타나지 않는다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <iostream> using namespace std; class Test { private: int a; public: Test() { a = 0; } ~Test() { } void Show() { cout << "a: " << a << endl; } friend void Change(Test& t, int c); }; void Change(Test& t, int c = 100) { t.a = c; } int main(int argc, char* argv[]) { Test t; t.Show(); Change(t, 10); t.Show(); return 0; } | cs |
Or, you can declare and define the friend function and set the default arguments at once.
아니면 friend 함수 선언부에서 함수 정의까지 작성하고 매개 변수를 설정해 준다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <iostream> using namespace std; class Test { private: int a; public: Test() { a = 0; } ~Test() { } void Show() { cout << "a: " << a << endl; } friend void Change(Test& t, int c = 100) { t.a = c; } }; int main(int argc, char* argv[]) { Test t; t.Show(); Change(t, 10); t.Show(); return 0; } | cs |
<Result>
