C++ 단일 레벨 상속

C++Beginner
지금 연습하기

소개

이 랩에서는 C++ 프로그래밍 언어에서 단일 레벨 상속 (Single Level Inheritance) 의 개념을 시연하는 방법을 배우게 됩니다. 부모 클래스와 자식 클래스, 즉 파생 클래스 (derived class) 가 부모 클래스 (base 또는 super class) 의 특징 (속성 및 메서드) 을 상속받는 두 개의 클래스를 생성할 것입니다.

main.cpp 파일 생성

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

touch ~/project/main.cpp

코드 작성

다음 코드를 복사하여 main.cpp 파일에 붙여넣습니다.

#include <iostream>
// 필요한 라이브러리 포함

using namespace std;

// "Shape"라는 부모 클래스 (base class) 선언
class Shape {
    public:
        float area(float l, float b) { // Shape 의 면적을 계산하는 메서드
            return (l * b);
        }

        float perimeter(float l, float b) { // Shape 의 둘레를 계산하는 메서드
            return (2 * (l + b));
        }
};

// Shape 클래스를 상속받는 "Rectangle"이라는 자식 클래스 (derived class) 선언
class Rectangle: private Shape {
    private:
        float length,
        breadth;

    public:
        Rectangle(): length(0.0), breadth(0.0) {} // Rectangle 의 기본 생성자

        void getDimensions() { // 사용자로부터 Rectangle 의 치수를 얻는 메서드
            cout << "\nEnter the length of the Rectangle: ";
            cin >> length;

            cout << "\nEnter the breadth of the Rectangle: ";
            cin >> breadth;
        }

        // Shape 클래스를 사용하여 Rectangle 의 둘레를 계산하는 메서드
        float perimeter() {
            // Shape 클래스의 perimeter() 메서드를 호출하여 반환합니다.
            return Shape::perimeter(length, breadth);
        }

        // Shape 클래스를 사용하여 Rectangle 의 면적을 계산하는 메서드
        float area() {
            // Shape 클래스의 area() 메서드를 호출하여 반환합니다.
            return Shape::area(length, breadth);
        }
};

int main() {
    // Rectangle 클래스의 객체 생성
    Rectangle rect;

    // 환영 메시지
    cout << "\n\nWelcome to Single Level Inheritance Program!\n";

    // 사용자에게 메시지
    cout << "\nRectangle class is derived from the Shape class.\n\n";

    // 사용자로부터 Rectangle 의 치수를 얻기
    rect.getDimensions();

    // 부모 클래스 Shape 을 사용하여 Rectangle 의 둘레를 계산하고 출력
    cout << "\nPerimeter of the Rectangle computed using the parent Class Shape: " << rect.perimeter() << "\n";

    // 부모 클래스 Shape 을 사용하여 Rectangle 의 면적을 계산하고 출력
    cout << "Area of the Rectangle computed using the parent Class Shape: " << rect.area() << "\n\n";

    return 0;
}

코드 컴파일 및 실행

다음으로, 다음 명령을 사용하여 코드를 컴파일합니다.

g++ main.cpp -o main && ./main

그런 다음, 다음 명령을 사용하여 코드를 실행합니다.

./main

출력 결과 이해

프로그램을 실행한 후, 다음과 같은 출력을 볼 수 있습니다.

Welcome to Single Level Inheritance Program!

Rectangle class is derived from the Shape class.

Enter the length of the Rectangle: 5

Enter the breadth of the Rectangle: 10

Perimeter of the Rectangle computed using the parent Class Shape: 30
Area of the Rectangle computed using the parent Class Shape: 50

프로그램은 사용자에게 사각형의 길이와 너비를 입력하라는 메시지를 표시합니다. 치수를 얻은 후, 부모 클래스 Shapeperimeter()area() 함수를 사용하여 둘레와 면적을 계산합니다.

요약

축하합니다! 단일 레벨 상속의 개념을 보여주는 C++ 프로그램을 성공적으로 작성했습니다. 다양한 도형으로 실험해 볼 수 있으며, 출력은 새로운 파생 클래스에 대한 계산을 정확하게 반영합니다.