추상 클래스와 순수 가상함수

조한별·2022년 4월 13일
0
// 추상 클래스 = 1가지 이상의 순수 가상함수가 있는 클래스
// 추상 클래스는 인스터스화(객체화)를 할 수 없다

#include <iostream>

using namespace std;

class Shape
{
public:
    virtual double getArea() const = 0;         //순수 가상함수 선언 및 정의 방식
    virtual ~Shape() {}
};



//부모 클래스가 추상 클래스일 경우에
//자식 클래스가 순수 가상함수에 대해서 정의를 하지 않을 경우엔
//그 자식 클래스도 추상 클래스가 된다.
class Circle : public Shape
{
private:
    double _radius;

public:
    Circle(double radius) :_radius(radius)
    {

    }

    virtual double getArea() const
    {
        return _radius * _radius * 3.14f;
    }
};

class Rectangle :public Shape
{
private:
    double _width;
    double _height;

public:
    Rectangle(double width, double height)
        :_width(width), _height(height)
    {

    }

    virtual double getArea() const override
    {
        return _width * _height;
    }
};

int main()
{
    Circle c(10);
    cout << c.getArea() << endl;

    Rectangle r(10, 20);
    cout << r.getArea() << endl;

    Shape* s0 = &c;
    Shape& s1 = r;

    cout << s0->getArea() << endl;
    cout << s1.getArea() << endl;
}

결과

314
200
314
200
profile
게임프로그래머 지망생

0개의 댓글