C++ 상속 - 추상 클래스, 순수 가상 함수

진경천·2023년 10월 25일
0

C++

목록 보기
54/90

순수 가상 함수

기존의 재정의가 가능한 함수를 가리키는 가상 함수와 다르게 순수 가상 함수는 파생 클래스에서 반드시 재정의해야 하는 멤버 함수를 의미한다.
일바적으로 함수의 동작을 정의하는 본체를 가지고 있지 않다.

virtual 멤버함수의 원형 = 0;

추상 클래스

하나 이상의 순수 가상 함수를 포함하는 클래스를 의미한다.

class 클래스명 {
public:
	virtual 멤버함수의 원형 = 0;
    virtual ~클래스명() { }
};

예제

#include <iostream>

using namespace std;

class Shape {
public:
	virtual double getArea() const = 0;
	// 도형을 만들기 위해 변의 길이 등을 반드시 재정의해야 함.
	virtual ~Shape() { }
};

class Circle : public Shape {
	// 추상 클래스를 상속하였기 때문에 Circle도 추상 클래스임
private:
	double _radius;

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

	}

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

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;
	}
};

class AreaAverage {
private:
	double _total = 0;
	int _size = 0;

public:
	double operator()(Shape& shape) {
		_size += 1;
		_total += shape.getArea();
		return _total / _size;
	}
};
// 추상 클래스를 파라미터로 받게 되면 특정 멤버함수만 가져올 수 있다.

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

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

	Shape* s0 = &c;
	Shape& s1 = r;
	cout << s0->getArea() << endl;
	cout << s1.getArea() << endl;
	// Shape 는 직접 생성을 못해도 포인터나 참조가 가능하다.

	AreaAverage aavg;
	cout << aavg(c) << endl;
	cout << aavg(r) << endl;
}
  • 실행 결과

    314
    200
    314
    200
    314
    257

profile
어중이떠중이

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN