각 상속 테스트

|

#include < iostream >
using namespace std;


class parent
{
public :
 parent(){value = 0;}
 void methodA(){cout << "methodA call!" << endl;}
protected :
 void methodB(){cout << "methodB call!" << endl;}
private :
 int value;
};


class child1 : public parent
{
public :
 child1(){value_child1 = 1;}
 void methodC(){cout << "methodC call!" << endl; methodB();} //부모로부터 상속받았기때문에 methodB에 접근허가
protected :
 void methodD(){cout << "methodD call!" << endl;}
private :
 int value_child1;
};


class child2 : protected parent
{
public :
 child2(){value_child2 = 2;}
 void methodE(){cout << "methodE call!" << endl; methodB();} //부모로부터 상속받았기때문에 methodB에 접근허가
protected :
 void methodF(){cout << "methodF call!" << endl; }
private :
 int value_child2;
};


class child3 : private parent
{
public :
 void methodG(){cout << "methodG call!" << endl; methodB();} //부모로부터 상속받았기때문에 methodB에 접근허가
};


void main()
{
 child1 childtest;
 childtest.methodA();
 //childtest.methodB();  //에러발생 protected 멤버 접근 불가
 childtest.methodC();
  //childtest.methodD();  //에러발생 protected 멤버 접근 불가
 //cout << childtest.value << endl; //에러발생 private 멤버 접근 불가
 //cout << childtest.value_child1 << endl; //에러발생 private 멤버 접근 불가

 cout << endl;


 child2 childtest2;
  //childtest2.methodA(); //에러발생 protected로 상속받았기때문에 public 이더라도 사용할 수 없음
 //childtest2.methodB(); //에러발생 protected 멤버 접근 불가

 childtest2.methodE();
  //childtest2.methodF(); //에러발생 protected 멤버 접근 불가
 //cout << childtest2.value << endl; //에러발생 private 멤버 접근 불가

 cout << endl;


 child3 childtest3;
 childtest3.methodG();
}


실행결과

methodA call!
methodC call!
methodB call!


methodE call!
methodB call!


methodG call!
methodB call!
Press any key to continue

출처 : 직접작성 및 Teach Yourself C++ - Visual Studio.NET 2003을 기준으로 작성됨


And