#11 [c++]상속

정상준·2022년 11월 5일
0

c++

목록 보기
7/25

📝상속

  • 상속이란?
    • 물질적인 상속, 유전적인 상속
  • C++의 상속
    • 기본 클래스의 속성과 기능을 파생 클래스에 물려줌
      • 기본클래스(base class): 상속해주는 클래스, 부모 클래스
      • 파생클래스(derived class): 상속을 받는 클래스, 자식클래스
    • 다중 상속
      • 여러 클래스를 상속 받는 기능
    • 코드의 재활용성 상승

📝상속의 장점

  • 모듈화
    • 직관적 단위 모듈 별 설계 및 구현 가능
    • 상속을 통해 간결한 설계 가능
  • 계층적 분류
    • 구조적 설계 용이
  • 생산성 향상
    • 재사용으로 인한 빠른 생산
    • 재사용성이 증가함

📝상속의 선언 방법

  • 형식
    • class 파생 클래스명 : 접근 지정자 기본 클래스명
    • class Multimedia TV : public TV
  • 상속의 결과
    • TV class:
      • showChanner()
    • MultimediaTV
      • showChannel()
      • playMovie()

✏️ 상속 예시

#include <iostream>
#include <string>

using namespace std;

/* 
Red:(3,4)
*/

class Shape {
private:
	int x, y; //(x,y) 좌표값
	int type; //0. 미지정, 1. 원, 2. 사각형
public:
	Shape() { type = 0; }
	void set(int x, int y) {
		this->x = x; this->y = y;
	}
	void showPoint() {
		cout << "(" << x << "," << y << ")" << endl;
	}
};

class Circle : public Shape {
	string color;
public:
	void setColor(string color) { this->color = color;}
	void showCircle();
};

void Circle::showCircle() {
	cout << color << ":";
	showPoint();
}

int main() {
	Shape p;
	Circle cp;
	cp.set(3, 4);
	cp.setColor("Red");
	cp.showCircle();
}
profile
안드로이드개발자

0개의 댓글