C++/summary

상속

gandus 2010. 9. 27. 10:11

class car
{}

class sportcar : public(접근자) car   // 상속을 표시한다.
{}

상속을 하는 이유는 중복되는 멤버 변수 및 함수를 피하기 위해서다.



접근 지정자에 대한 권한.


 

접근 지정자

현재 클래스

자식 클래스

외부

private

×

×

protected

×

public





상속과 생성자/소멸자

자식 객체를 생성하면 부모 생성자 호출 한 다음 자식 생성자 생성
-> 자식 소멸자 - > 부모 소멸자 호출 이러한 순서로 움직인다.


클래스간 관계성

is - a 관계 : 상속으로 구현한다.
has - a 관계 :  포함

ex) 컴퓨터 클래스.

1.) class ClassRoom : public 컴퓨터 {}

2.) class ClassRoom{
   컴퓨터  c;
}
여기서는 2번이 맞는것이다.



부모 생성자의 명시적 호출

class Shape {

           int x, y;

public:

           Shape() {         

                     cout << "Shape 생성자() " << endl;

           }

           Shape(int xloc, int yloc) : x(xloc), y(yloc){    

                     cout << "Shape 생성자(xloc, yloc) " << endl;

           }

           ~Shape() {        

                     cout << "Shape 소멸자() " << endl;

           }

};

 

class Rectangle : public Shape {

           int width, height;

public:

           Rectangle(int x=0, int y=0, int w=0, int h=0);

           ~Rectangle(){               

                     cout << "Rectangle 소멸자()" << endl;

           }

};

Rectangle::Rectangle(int x, int y, int w, int h) : Shape(x, y) {             

                     width = w;

                     height = h;

                     cout << "Rectangle 생성자(x, y, w, h)" << endl;

}

: Shape(x,y) 가 없다면 기본 생성자가 호출이 된다.