• 목록
  • 아래로
  • 위로
  • 쓰기
  • 검색

C언어 가상함수(Shape 클래스)

너에게제공 너에게제공
519 0 0
class Shape 
{
protected:  
    int x, y; 
public:
    Shape(int x=0, int y=0) { this->x = x; this->y = y;} 
    void setOrigin(int x, int y) { this->x = x; this->y = y; }
    virtual void draw() { cout <<"Shape Draw" << endl; }
    void printPosition() { cout << "x : " << x << ", y : " << y << endl; }
};

class Rectangle : public Shape 
{
        private: 
        int width, height;
        public: 
    Rectangle (int x=0, int y=0, int w=5, int h=10) :Shape(x,y)
        {
                width=w;
                height=h;
        }
    void setWidth(int w) 
        {
                width=w;
        }
    void setHeight(int h) 
        {
                height=h; 
        }
    void draw() 
        {
                cout<<"Rectangle draw"<<endl;
        }
    void printPosition() 
        {   
                Shape::printPosition();
                cout<<"width:"<<width<<"height:"<<height<<endl;
        }
};
class Circle : public Shape 
{
private: int radius;
public: Circle(int x=0, int y=0, int r=5):Shape(x,y)
                {
                        radius=r;
                }
                void setRadius(int r)
                {
                        radius=r;
                }
                void draw()
                {
                        cout<<"Circle draw"<<endl;
                }
                void printPosition()
                {
                        Shape::printPosition();
                        cout<<"r:"<<radius;
                }
};

int main() 
{
    Shape *ps = new Rectangle();  // 상향 형변환            
    ps->draw();        

    Shape *ps1 = new Circle();   // 상향형변환
    ps1->draw();

    delete ps;    
    delete ps1;
}
신고공유스크랩

댓글 0

댓글 쓰기
권한이 없습니다. 로그인
에디터 모드

신고

"님의 댓글"

이 댓글을 신고하시겠습니까?

댓글 삭제

"님의 댓글"

이 댓글을 삭제하시겠습니까?

공유

퍼머링크