250x250
Notice
Recent Posts
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
관리 메뉴

일상 코딩

[C++/11.02] 상속 기본 2 본문

C++/따배C++ 11강 상속

[C++/11.02] 상속 기본 2

polarcompass 2021. 11. 6. 23:01
728x90

1. main.cpp

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

using namespace std;

int main()
{

    Student std("Jack Jack");
    std.setName("Jack Jack 2");
    std.getName();

    Teacher teacher1("Dr. H");
    teacher1.setName("Dr. K");

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

    cout << std << endl;

    std.doNothing();
    teacher1.doNothing();

    std.study();
    teacher1.teach();

    Person person;
    person.setName("Mr. Incredible");
    person.getName();
    person.doNothing();

    // 자식 함수를 부모가 쓸 수는 없다.
    // person.study();
    // person.teach();

    return 0;
}

2. Person.h

#pragma once

#include <string>
#include <iostream>

class Person
{
private:
    std::string m_name;

public:
    // Person()
    //     : m_name("No name")
    // {}

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

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

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

    void doNothing() const
    {
        std::cout << m_name << " is doing nothing." << std::endl;
    }
};

3. Student.h

#pragma once

// #include <iostream>
// #include <string>
#include "Person.h"

class Student : public Person
{
private:
    int m_intel; // intelligence; 지능

    // TODO : add more members like address, phone, favorate food, habits,...
public:
    Student(const std::string &name_in = "No Name", const int &intel_in = 0)
        // : m_name(name_in), m_intel(intel_in)
        : Person(name_in)
        , m_intel(intel_in)
    {}

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

    int getIntel()
    {
        return m_intel;
    }

    void study()
    {
        std::cout << getName() << " is studying " << std::endl;
    }

    friend std::ostream &operator<<(std::ostream &out, Student &student)
    {
        out << student.getName() << " " << student.m_intel;
        return out;
    }
};

4. Teacher.h

#pragma once

// #include<string>
#include "Person.h"

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

    void teach()
    {
        std::cout << getName() << " is teaching " << std::endl;
    }

    friend std::ostream &operator<<(std::ostream &out, Teacher &teacher)
    {
        // out << teacher.m_name;
        out << teacher.getName();
        return out;
    }
};
728x90

'C++ > 따배C++ 11강 상속' 카테고리의 다른 글

[C++/11.03] 유도된 클래스들의 생성 순서  (0) 2021.11.07
[C++/11.01] 상속 기본 1  (0) 2021.11.06