C++ 계층적 상속 프로그램

C++Beginner
지금 연습하기

소개

이 랩에서는 계층적 상속 (Hierarchical Inheritance) 의 개념을 보여주는 C++ 프로그램을 만드는 방법을 시연합니다. 클래스와 객체를 사용하여 이 주제를 더 잘 이해하기 위해 간단한 프로그램을 작성할 것입니다.

main.cpp 생성

다음 명령을 사용하여 ~/project 디렉토리에 main.cpp라는 새 파일을 생성합니다.

touch ~/project/main.cpp

Shape 클래스 작성

가장 먼저 해야 할 일은 Shape 클래스를 정의하는 것입니다. 이 클래스는 RectangleTriangle 클래스의 부모 클래스 역할을 합니다. 이 클래스에서는 도형의 너비와 높이를 저장할 두 개의 protected 멤버 변수 widthheight를 생성합니다.

그런 다음, 이러한 치수를 설정하고 콘솔에 메시지를 출력하는 public 멤버 함수 setDimensions를 생성합니다.

다음은 main.cpp에 추가해야 하는 Shape 클래스에 대한 코드 블록입니다.

#include <iostream>
using namespace std;

class Shape {
    //protected member variables are only accessible within the class and its descendant classes
    protected:
        float width, height;
    //public members are accessible everywhere
    public:
        void setDimensions(float w, float h) {
            cout << "Setting the Dimensions using the parent Class: Shape\n";
            cout << "The dimensions are: " << w << " and " << h << "\n\n";

            width = w;
            height = h;
        }
};

Rectangle 클래스 작성

다음으로, Shape 클래스를 상속받는 Rectangle 클래스를 생성합니다. 여기서는 area() 함수를 사용하여 사각형의 면적을 계산하기 위해 메서드 오버라이딩 (method overriding) 기술을 사용합니다.

다음은 main.cpp에 추가해야 하는 Rectangle 클래스에 대한 코드 블록입니다.

class Rectangle: public Shape {
    //Method Overriding
    public:
        float area() {
            return (width * height);
        }
};

Triangle 클래스 작성

이제 Shape 클래스를 상속받는 Triangle 클래스를 생성해 보겠습니다. 여기서는 area() 함수를 사용하여 삼각형의 면적을 계산하기 위해 메서드 오버라이딩 (method overriding) 을 사용합니다.

다음은 main.cpp에 추가해야 하는 Triangle 클래스에 대한 코드 블록입니다.

class Triangle: public Shape {
    //Method Overriding
    public:
        float area() {
            return (width * height / 2);
        }
};

main() 함수 작성

이제 main() 함수를 작성할 차례입니다. 여기서는 RectangleTriangle 클래스 모두에 대한 객체를 생성하고 해당 치수를 설정합니다.

그런 다음 area() 함수를 사용하여 각 객체를 통해 RectangleTriangle의 면적을 계산합니다.

다음은 main.cpp에 추가해야 하는 main() 함수에 대한 코드 블록입니다.

int main() {

    cout << "\n\nWelcome to LabEx :-)\n\n\n";
    cout << "===== Program to demonstrate the concept of Hierarchical Inheritance in CPP =====\n\n";

    //Declaring the Class objects to access the class members
    Rectangle rectangle;
    Triangle triangle;

    rectangle.setDimensions(5, 3);
    triangle.setDimensions(2, 5);

    cout << "\nArea of the Rectangle computed using Rectangle Class is : " << rectangle.area() << "\n\n\n";
    cout << "Area of the Triangle computed using Triangle Class is: " << triangle.area();

    cout << "\n\n\n";

    return 0;
}

프로그램 컴파일 및 실행

터미널에서 프로그램을 실행하려면 먼저 ~/project로 이동합니다. 그런 다음 다음 명령을 입력하여 main.cpp 파일을 컴파일합니다.

g++ main.cpp -o main

그 후, 다음 명령으로 프로그램을 실행합니다.

./main

터미널에서 출력을 확인할 수 있습니다.

요약

이 랩에서는 CPP 에서 계층적 상속 (Hierarchical Inheritance) 의 개념을 시연하는 방법을 배웠습니다. Shape 클래스를 생성했는데, 이는 RectangleTriangle의 부모 클래스였습니다. 그런 다음 각 자식 클래스에 대한 객체를 생성하고 메서드 오버라이딩 (method overriding) 을 사용하여 사각형과 삼각형의 면적을 구했습니다.

이 랩을 통해 C++ 에서 계층적 상속이 어떻게 작동하는지에 대한 이해를 높이는 데 도움이 되었기를 바랍니다. 궁금한 점이 있으면 아래 댓글 섹션을 통해 언제든지 문의하십시오.