본문 바로가기
대외활동/한화비전 VEDA

상속, 오버라이딩, 추상화

by hoshi03 2024. 7. 29.

• 상속

 

기본 클래스

 

 

#include "Point.h"

void Point::showPoint() {
    std::cout << "(" << x << "," << y << ")" << "\n";
}

void Point::setXY(int x, int y) {
    this->x = x;
    this->y = y;
}

 

point를 상속받는 클래스 ColorPoint

헤더

#pragma once
#include "Point.h"
#include <iostream>
#include <string>

class ColorPoint : public Point {
    std::string color;
public:
    void setColor(std::string color);
    void showColorPoint();
};

구현

#include "ColorPoint.h"

void ColorPoint::showColorPoint() {
    std::cout << color << ":";
    showPoint();
}

void ColorPoint::setColor(std::string color) {
    this->color = color;
}

 

메인

#include <iostream>
#include "ColorPoint.h"
#include "Point.h"

using namespace std;

int main() {
	ColorPoint colorPoint;

	colorPoint.setColor("red");
	colorPoint.setXY(5, 5);
	colorPoint.showColorPoint();

}

 

• 업캐스팅 & 다운캐스팅

업캐스팅 : 자식 클래스 객체가 상위 클래스 포인터를 가리키는 것

다운캐스팅 : 기본 클래스 객체가 자식 클래스 포인터를 가리키는 것

int main() {
	ColorPoint cp;
	ColorPoint* pDer;
	Point* pbase = &cp; // 업 캐스팅
	pbase->setXY(3, 4);
	pbase->showPoint();

	pDer = (ColorPoint*)pbase; //다운캐스팅
	pDer->setColor("RED ");
	pDer->showColorPoint();
}

 

#include "man.h"
#include "woman.h"

int main()
{
	//Man m1("홀길동", 23);
	//Woman w1("강아지", 33);
	//m1.show();
	//w1.show();

	Man* m = new Man();
	Woman* w = new Woman();

	//업캐스팅
	Human* h_m = m;
	Human* h_w = w;

	h_m->show();
	h_w->show();

	//다운캐스팅
	Man* d_man; 
	d_man = (Man*)h_m;

	Woman* d_woman; 
	d_woman = (Woman*)h_w;

	h_m->show();
	h_w->show();


	return 0;
}

 다중 상속

class MusicPhone : public MP3, public MobilePhone 형태로 여러 클래스를 상속 받을 수 있다

 

• 가상 상속 (Virtual)

 

다중 상속시 모호함 때문에 virtual 키워드를 사용해서 파생 클래스에서 함수 재정의 가능하게 오버라이딩

책 408p 예제, 돌려보기

 

• 오버라이딩과 동적 바인딩

 

아래의 예제는 동적 바인딩이 일어나서 모두 하위 클래스의 메서드가 호출되게 된다

#include <iostream>

using namespace std;

class Base {
public: virtual void bf() { cout << "base " << "\n"; }
};

class Derived : public Base {
public: void bf() { cout << "Derived " << "\n"; }
};
class GrandDrived : public Derived {
public: void bf() { cout << "GrandDrived " << "\n"; }
};

int main()
{
	GrandDrived g;
	Base *bp;
	Derived *dp;
	GrandDrived *gp;
	bp = dp = gp = &g;

	bp->bf();
	dp->bf();
	gp->bf();

	return 0;
}

 

• 멤버 초기화 리스트

선언과 함께 초기화 하는 형식 

생성자 뒤에 콜론(:)을 붙이고 멤버 변수를 초기화

 

• 순수 가상 함수

코드가 없고 선언만 있는 가상 메서드, 실행이 목적이 아니라 상속 받아서 재정의 하는 것이 목적이다

 

• 추상 클래스

하나 이상의 순수 가상 함수를 가진 클래스 

추상 클래스는 상속을 위한 기본 클래스로 사용한다

 

• 상속을 이용한 다형성 구현 예제

employee 클래스를 두고 

일용직과 정규직으로 나눠서 급여를 계산하는 코드

https://github.com/Hoshi03/VEDA_Practice/tree/main/cpp_practice/empl

 

VEDA_Practice/cpp_practice/empl at main · Hoshi03/VEDA_Practice

Contribute to Hoshi03/VEDA_Practice development by creating an account on GitHub.

github.com