Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++의 상속과 우정

<시간/>

C++에서 우정은 상속되지 않습니다. 즉, 하나의 부모 클래스에 친구 기능이 있는 경우 자식 클래스는 해당 기능을 친구로 가져오지 않습니다.

이 예제에서는 display() 함수가 MyBaseClass의 친구이지만 MyDerivedClass의 친구가 아니기 때문에 오류를 생성합니다. display()는 MyBaseClass의 private 멤버에 액세스할 수 있습니다.

예시

#include <iostream>
using namespace std;
class MyBaseClass {
   protected:
      int x;
   public:
      MyBaseClass() {
         x = 20;
      }
      friend void display();
};
class MyDerivedClass : public MyBaseClass {
   private:
      int y;
   public:
      MyDerivedClass() {
         x = 40;
      }
};
void display() {
   MyDerivedClass derived;
   cout << "The value of private member of Base class is: " << derived.x << endl;
   cout << "The value of private member of Derived class is: " << derived.y << endl;
}
main() {
   display();
}

출력

[Error] 'int MyDerivedClass::y' is private
[Error] within this context