C++ Programming

C++ 부모 자식 상속

psy_er 2021. 12. 10. 00:42
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