qingfro9님의 블로그 입니다.

C++ 정적바인딩, 동적바인딩 예제 코드 본문

개발언어

C++ 정적바인딩, 동적바인딩 예제 코드

qingfro9 2020. 6. 21. 17:57

웹서비스로 빌드해서 결과를 보여주는 웹서비스가 있었다.!

- Coliru.stacked-crooked : http://coliru.stacked-crooked.com/

 

Coliru

 

coliru.stacked-crooked.com


정적 바인딩 코드

#include <iostream>
class Shape{
    public:
        void draw(){
            std::cout << "draw shape" << std::endl;
        }
};


class Circle : public Shape{
    public:
        void draw(){
            std::cout << "draw circle" << std::endl;
        }
};


class Rectangle : public Shape{
    public:
        void draw(){
            std::cout << "draw rectangle" << std::endl;
        }
};


class Square : public Rectangle{
    public:
        void draw(){
            std::cout << "draw square" << std::endl;
        }
};


int main()
{
    Square* sq = new Square;
    Circle* cc = new Circle;
    Rectangle* rect = new Rectangle;
    Shape* ptr_shape;
    
    std::cout <<"Static binding"<<std::endl;
    
    cc->draw();
    rect->draw();
    sq->draw();
    
    ptr_shape = cc;
    ptr_shape->draw();
    
    ptr_shape = rect;
    ptr_shape->draw();
    
    ptr_shape = sq;
    ptr_shape->draw();
    
    return 0;
    
}

 

 

동적 바인딩 코드

#include <iostream>


class Shape{
    public:
        virtual void draw(){
            std::cout << "draw shape" << std::endl;
        }
};


class Circle : public Shape{
    public:
        void draw(){
            std::cout << "draw circle" << std::endl;
        }
};


class Rectangle : public Shape{
    public:
        void draw(){
            std::cout << "draw rectangle" << std::endl;
        }
};


class Square : public Rectangle{
    public:
        void draw(){
            std::cout << "draw square" << std::endl;
        }
};


int main()
{
    Square* sq = new Square;
    Circle* cc = new Circle;
    Rectangle* rect = new Rectangle;
    Shape* ptr_shape;
    
    std::cout <<"Dynamic binding"<<std::endl;
    
    cc->draw();
    rect->draw();
    sq->draw();
    
    ptr_shape = cc;
    ptr_shape->draw();
    
    ptr_shape = rect;
    ptr_shape->draw();
    
    ptr_shape = sq;
    ptr_shape->draw();
    
    return 0;
    
}

 

Comments