-----ETC-----/C++ 마스터 시리즈

[C++ 마스터] Day 15: 상속과 다형성

cogito21_cpp 2024. 8. 1. 22:28
반응형

상속 (Inheritance)

상속은 기존 클래스(기본 클래스 또는 부모 클래스)를 기반으로 새로운 클래스(파생 클래스 또는 자식 클래스)를 정의하는 기능입니다. 상속을 사용하면 코드의 재사용성을 높이고, 클래스 간의 계층 구조를 만들 수 있습니다.

 

1. 기본 클래스와 파생 클래스

기본 클래스를 상속하여 파생 클래스를 정의할 수 있습니다.

class Base {
public:
    void show() {
        cout << "Base class show function" << endl;
    }
};

class Derived : public Base {
public:
    void display() {
        cout << "Derived class display function" << endl;
    }
};

int main() {
    Derived obj;
    obj.show();    // Base class show function
    obj.display(); // Derived class display function
    return 0;
}

 

2. 접근 지정자와 상속

파생 클래스는 기본 클래스의 접근 지정자에 따라 멤버에 접근할 수 있습니다. public, protected, private 상속이 있습니다.

class Base {
protected:
    int protectedVar;
public:
    int publicVar;
};

class Derived : public Base {
public:
    void setValues(int p, int q) {
        protectedVar = p;  // 접근 가능
        publicVar = q;     // 접근 가능
    }

    void display() {
        cout << "Protected Var: " << protectedVar << endl;
        cout << "Public Var: " << publicVar << endl;
    }
};

int main() {
    Derived obj;
    obj.setValues(10, 20);
    obj.display();
    return 0;
}

 

다형성 (Polymorphism)

다형성은 같은 인터페이스를 통해 다른 동작을 구현하는 능력입니다. C++에서는 주로 가상 함수와 함께 사용됩니다.

 

1. 가상 함수 (Virtual Function)

가상 함수는 파생 클래스에서 재정의될 수 있는 함수입니다. 기본 클래스에서 virtual 키워드를 사용하여 선언합니다.

class Base {
public:
    virtual void show() {
        cout << "Base class show function" << endl;
    }
};

class Derived : public Base {
public:
    void show() override {
        cout << "Derived class show function" << endl;
    }
};

int main() {
    Base* basePtr;
    Derived derivedObj;
    basePtr = &derivedObj;

    basePtr->show(); // Derived class show function
    return 0;
}

 

2. 순수 가상 함수 (Pure Virtual Function)

순수 가상 함수는 파생 클래스에서 반드시 재정의해야 하는 가상 함수입니다. 순수 가상 함수가 하나 이상 포함된 클래스를 추상 클래스라고 합니다.

class Shape {
public:
    virtual void draw() = 0;  // 순수 가상 함수
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing Circle" << endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        cout << "Drawing Square" << endl;
    }
};

int main() {
    Shape* shape1 = new Circle();
    Shape* shape2 = new Square();

    shape1->draw(); // Drawing Circle
    shape2->draw(); // Drawing Square

    delete shape1;
    delete shape2;
    return 0;
}

 

예제 문제

문제 1: 동물 클래스와 이를 상속받는 고양이와 개 클래스 작성

동물 클래스를 작성하고, 이를 상속받는 고양이와 개 클래스를 작성하세요. 각 클래스는 동물이 소리를 내는 함수를 가지고 있어야 합니다.

 

해설:

#include <iostream>
#include <string>

using namespace std;

class Animal {
public:
    virtual void makeSound() {
        cout << "Some generic animal sound" << endl;
    }
};

class Cat : public Animal {
public:
    void makeSound() override {
        cout << "Meow" << endl;
    }
};

class Dog : public Animal {
public:
    void makeSound() override {
        cout << "Bark" << endl;
    }
};

int main() {
    Animal* animal1 = new Cat();
    Animal* animal2 = new Dog();

    animal1->makeSound(); // Meow
    animal2->makeSound(); // Bark

    delete animal1;
    delete animal2;
    return 0;
}

 

이 프로그램은 동물 클래스를 상속받아 고양이와 개 클래스를 작성하고, 각 클래스가 동물이 소리를 내는 함수를 구현합니다.

 

문제 2: 도형 클래스와 이를 상속받는 원과 사각형 클래스 작성

도형 클래스를 작성하고, 이를 상속받는 원과 사각형 클래스를 작성하세요. 각 클래스는 도형의 면적을 계산하는 함수를 가지고 있어야 합니다.

 

해설:

#include <iostream>
#include <cmath>

using namespace std;

class Shape {
public:
    virtual double area() = 0;  // 순수 가상 함수
};

class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}

    double area() override {
        return M_PI * radius * radius;
    }
};

class Rectangle : public Shape {
private:
    double width;
    double height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() override {
        return width * height;
    }
};

int main() {
    Shape* shape1 = new Circle(5.0);
    Shape* shape2 = new Rectangle(4.0, 6.0);

    cout << "Circle area: " << shape1->area() << endl;      // Circle area: 78.5398
    cout << "Rectangle area: " << shape2->area() << endl;   // Rectangle area: 24

    delete shape1;
    delete shape2;
    return 0;
}

 

이 프로그램은 도형 클래스를 상속받아 원과 사각형 클래스를 작성하고, 각 클래스가 도형의 면적을 계산하는 함수를 구현합니다.

 

문제 3: 차량 클래스와 이를 상속받는 자전거와 자동차 클래스 작성

차량 클래스를 작성하고, 이를 상속받는 자전거와 자동차 클래스를 작성하세요. 각 클래스는 차량의 최고 속도를 반환하는 함수를 가지고 있어야 합니다.

 

해설:

#include <iostream>

using namespace std;

class Vehicle {
public:
    virtual int topSpeed() = 0;  // 순수 가상 함수
};

class Bicycle : public Vehicle {
public:
    int topSpeed() override {
        return 25;  // 자전거의 최고 속도
    }
};

class Car : public Vehicle {
public:
    int topSpeed() override {
        return 200;  // 자동차의 최고 속도
    }
};

int main() {
    Vehicle* vehicle1 = new Bicycle();
    Vehicle* vehicle2 = new Car();

    cout << "Bicycle top speed: " << vehicle1->topSpeed() << " km/h" << endl;  // Bicycle top speed: 25 km/h
    cout << "Car top speed: " << vehicle2->topSpeed() << " km/h" << endl;      // Car top speed: 200 km/h

    delete vehicle1;
    delete vehicle2;
    return 0;
}

 

이 프로그램은 차량 클래스를 상속받아 자전거와 자동차 클래스를 작성하고, 각 클래스가 차량의 최고 속도를 반환하는 함수를 구현합니다.

 

다음 단계

15일차의 목표는 C++의 상속과 다형성에 대해 학습하는 것이었습니다. 다음 날부터는 가상 함수와 추상 클래스에 대해 더 깊이 있게 다룰 것입니다.

 

내일은 "가상 함수와 추상 클래스"에 대해 다룰 예정입니다. 질문이나 피드백이 있으면 댓글로 남겨 주세요!

반응형