C++/Class 2021. 3. 19. 19:47

상속 Teacher-Student 예제

main.cpp

#include "Student.h"
#include "Teacher.h"

int        main()
{
    using namespace std;

    Student std("Jack Jack");

    std.setName("New Jack");
    std.getName();

    cout << std.getName() << endl;

    Teacher teacher1("Dash");

    teacher1.setName("Dr. K");

    cout << teacher1.getName() << endl;

    cout << std << endl;
    cout << teacher1 << endl;
}

/* stdout
New Jack
Dr. K
New Jack 0
Dr. K
*/

Person.h

#pragma once

#include <iostream>

class Person
{
    std::string name_;

public:
    Person(const std::string & name_in)
        : name_{name_in}
    {}

    std::string    getName() const
    {
        return name_;
    }

    void    setName(const std::string& name_in)
    {
        name_ = name_in;
    }
};

Student.h

#pragma once

#include "Person.h"

class Student : public Person
{
    int        intel_;

public:
    Student(const std::string& name_in = "No Name", const int& intel_in = 0)
        : Person(name_in), intel_{ intel_in }
    {}

    void    setIntel(const int& intel_in)
    {
        intel_ = intel_in;
    }

    int        getIntel()
    {
        return intel_;
    }

    friend std::ostream& operator << (std::ostream& out, const Student& student)
    {
        out << student.getName() << ' ' << student.intel_;
        return out;
    }
};

Teacher.h

#pragma once

#include "Person.h"

class Teacher : public Person
{

public:
    Teacher(const std::string& name_in = "No Name")
        : Person(name_in)
    {}

    friend std::ostream& operator << (std::ostream& out, const Teacher& teacher)
    {
        out << teacher.getName();
        return out;
    }
};

'C++ > Class' 카테고리의 다른 글

C++ 유도된 클래스들의 소멸 순서  (0) 2021.03.19
C++ 유도된 클래스들의 생성 순서  (0) 2021.03.19
C++ 상속 기본 예제  (0) 2021.03.19
C++ 상속 (Inheritance)  (0) 2021.03.19
C++ 의존 관계 (Dependency)  (0) 2021.03.19