728x90
C++ 부모 자식 상속
상속 : 연관된 클래스 공통, 배열 생성 위해 public으로 선언
부모 클래스 private 멤버에 직접 접근하지 못해 access 함수를 사용해 접근한다.
<부모. h 가상 함수>
//부모.h 가상함수
class Person{
int age;
char name[50];
public:
Person(const char* name, int age);
void WhatYourName() const;
void HowOldAreYou() const;
const char* GetName() const {return name};
virtual void WhoAreYou() const; // 부모의 가상함수 선언시에만 virtual 키워드를 붙인다.
};
<자식. h 생성자 char* 포인터>
// 자식.h 생성자 char* 포인터
#define _CRT_SECURE_NO_WARNINGS
#ifndef _UNI_
#define _UNI_
#include <cstring>
#include "Person.h"
class UnivStudent : public Person { // Person으로부터 파생된 클래스
char* major; // 멤버 추가
public:
UnivStudent(const char* name, int age, const char* major);
~UnivStudent();
void WhoAreYou() const; // 자식에서 재정의
};
inline UnivStudent::UnivStudent(const char* name, int age, const char* major)
:Person(name,age){
this->major = new char [strlen(major)+1];
strcpy(this->major,major);
}
inline UnivStudent::~UnivStudent(){
cout << "~UnivStudent()" << endl;
delete [] major; // 소멸자에서 동적할당 해제
}
<상속. cpp>
// 상속.cpp
#include "UnivStudent.h"
#include <iostream>
using namespace std;
void UnivStudent::WhoAreYou() const{
this->WhatYouName();
HowOldAreYou();
Person::WhoAreYou(); // 은폐된 부모 메서드 호출
cout << "major : " << major << endl; // 추가된 멤버 포함 함수 재정의
}
728x90
'C++ Programming' 카테고리의 다른 글
C++ 제네릭 템플릿 클래스 (0) | 2021.12.14 |
---|---|
C++ 다형성 다운 캐스팅 업 캐스팅 (0) | 2021.12.12 |
[ C++ ] 레퍼런스 Reference 캡슐화 Encapsulation 정보은닉 Private (1) | 2021.11.08 |
[ C++ ] Class 클래스 정의와 객체 선언 (2) | 2021.11.07 |
[ C++ ] 반환 자료형의 세가지 형태, 매개변수의 세가지 형태 (1) | 2021.11.06 |