'2019/11/29'에 해당되는 글 1건

C++ 클래스 상속

C++/C++ 문법 2019. 11. 29. 21:24
728x90

C++에서 클래스 상속(inheritance)이란 기존에 정의되어 있는 클래스의 모든 멤버 변수와 멤버 함수를 물려받아, 새로운 클래스를 작성하는 것을 의미한다.
ㅇ 기존에 정의되어 있던 클래스를 base class 또는 parent class 또는 super class 라고 한다.
ㅇ 이를 상속받아(→모든 특성을 물려받아) 새로 만들어지는 클래스를 파생(derived) 클래스 또는 자식 클래스, 하위(sub) 클래스라고 한다.
ㅇ 기존에 작성된 클래스를 재활용할 수 있다.
ㅇ class 파생클래스명 : public 부모클래스명 {
       // 접근 제어 지시자 : public, protected, private

       // 상속시 부모 클래스에서 접근 가능한 멤버는 protected와 public 뿐이다.
   }


접근제어 지시자

 public

 클래스 외부 접근 허용

 자식 클래스 접근 허용

 클래스 내부 접근 허용

 proteced 로 상속을 받으면 부모 클래스를 proteced 로 상속함

 protected

 클래스 외부 접근 불가

 자식 클래스 접근 허용

 클래스 내부 접근 허용

 

 private

 클래스 외부 접근 불가

 자식 클래스 접근 불가

 클래스 내부 접근 허용

 


예제는 헤더파일(선언부)와 cpp 파일(정의부)를 분리하는 걸 고려하여 코드를 작성했다.

예제1

#include <iostream>
#include <string>

using namespace std;

class Person {
private:
    string name;
    int age;
public:
    Person(); // 기본 생성자
    Person(const string& name, int age);
    ~Person(); // 소멸자

    void setName(string name);
    void setAge(int age);

    string getName();
    int getAge();
};

Person::Person() {
    cout << " Person 기본 생성자 호출- 메모리 주소 : " << this << endl;
    this->name = "";
    this->age = 0;
}

Person::Person(const string& name, int age) {
    cout << " Person 매개변수 2개 생성자 호출- 메모리 주소 : " << this << endl;
    this->name = name;
    this->age = age;
}

Person::~Person() {
    cout << " ~Person() 호출- 메모리 주소 : " << this << endl;
}

void Person::setName(string name) {
    this->name = name;
}

void Person::setAge(int age) {
    this->age = age;
}

string Person::getName() {
    return this->name;
}

int Person::getAge() {
    return this->age;
}

class UStudent : public Person { // 접근 제어 지시자를 변경해보면서 에러 발생을 확인해 보자
private:
    string id; // 학번
    string major; // 전공과목
public:
    UStudent();
    UStudent(const string& id, const string& major, const string& name, int age);
    ~UStudent();

    void setId(string id);
    void setMajor(string major);

    string getId();
    string getMajor();

    void Display(); //메시지 출력
};

UStudent::UStudent() {
    cout << " UStudent 기본 생성자 호출- 메모리 주소 : " << this << endl;
}

UStudent::UStudent(const string& id, const string& major, const string& name, int age) : Person(name, age) {
    cout << " UStudent 매개변수 4개 생성자 호출- 메모리 주소 : " << this << endl;
    this->id = id;
    this->major = major;
}

UStudent::~UStudent() {
    cout << " ~UStudent() 호출- 메모리 주소 : " << this << endl;
}

void UStudent::setId(string id) {
    this->id = id;
}

void UStudent::setMajor(string major) {
    this->major = major;
}

string UStudent::getId() {
    return this->id;
}

string UStudent::getMajor() {
    return this->major;
}

void UStudent::Display() {
    cout << " 성명 : " << this->getName() << ", 나이 : " << this->getAge() << ", 학번 : " << this->getId() << ", 전공 : " << this->getMajor() << endl;
}

int main() {

    UStudent std1; // 파생 클래스의 객체를 생성하면, 제일 먼저 기초 클래스의 생성자를 호출
    std1.setName("이순신");
    std1.setAge(20);
    std1.setId("20190001");
    std1.setMajor("전기전자공학부");
    std1.Display();

    cout << endl;

    UStudent std2("20160002", "사회복지학부", "홍길동", 23);
    std2.Display();

    cout << endl;
    // 객체가 소멸되는 순서는 객체가 생성된 순서의 반대다.

// 객체가 소멸되는 순서는 객체가 생성된 순서의 반대다.

출처: https://link2me.tistory.com/1756?category=1075719 [소소한 일상 및 업무TIP 다루기]
// 객체가 소멸되는 순서는 객체가 생성된 순서의 반대다.

출처: https://link2me.tistory.com/1756?category=1075719 [소소한 일상 및 업무TIP 다루기]

}

실행결과



참고하면 도움될 게시글

상속과 접근 제어 유투브 강좌 : https://www.youtube.com/watch?v=yWI8GTLsBR8

상속 접근 지정자 : https://thrillfighter.tistory.com/531


블로그 이미지

Link2Me

,