상세 컨텐츠

본문 제목

Protected란?

C++/클래스

by nowpassion 2008. 5. 5. 13:48

본문

1. 접근지정자의 종류로 상속관계에 있는 클래스 까지만 접근을 허용하는 접근자입니다.

- 예제)

/*24.cpp*/
#include <iostream>

using std::endl;
using std::cout;


class Point
{
    int x_ptr;
    int y_ptr;
   
protected:
    int z_ptr;
   
public:
    Point(int _x = 0, int _y = 0){
    cout << "Point() 호출" << endl;
        x_ptr = _x;
        y_ptr = _y;
 }
   
    ~Point(){
     cout << "~Point() 호출" << endl;
 }
  
 void getPoint(){
     cout << "X좌표 :" << x_ptr << endl;
     cout << "Y좌표 :" << y_ptr << endl;
    }
};

class Line : public Point
{
    int length;

public:
    Line(int _x = 0, int _y = 0) : Point(_x, _y){
        length = _x + _y;
       
        //상속 관계에 있으므로 접근 가능
        z_ptr = _x * _y;
       
        // private이므로 접근 불가
        x_ptr = _x;
       
        cout << "Line() 호출" << endl;
    }
 
 ~Line(){
  cout << "~Line() 호출" << endl;
 }
 
    int getLine(){
        return length; 
       }
};

int main()
{
     Line line(3,8);
     cout << "길이는 " << line.getLine() << endl;
     // system("pause");
     return 0;
}

 - 실행결과

사용자 삽입 이미지

'C++ > 클래스' 카테고리의 다른 글

클래스 포인터의 할당 범위  (0) 2008.05.05
이니셜라이져가 더좋은 이유  (0) 2008.05.05
생성자, 소멸자 호출 순서  (0) 2008.05.05
Static with Class  (0) 2008.05.01
const도 오버로딩의 조건에 포함  (0) 2008.05.01

관련글 더보기