추상 클래스의 순수 가상함수가 연산자함수다. 이를 구체화 하는 파생클래스에서는 업캐스팅과 다운캐스팅의 과정이 필요하다.

업캐스팅 : 기본클래스 포인터가 파생클래스를 가리킨다 -> 포인터는 기본클래스의 멤버만 접근 가능

다운캐스팅 : 파생클래스 포인터가 기본클래스를 가리킨다 -> 포인터는 기본 및 파생 클래스의 멤버에 접근 가능

 

업, 다운캐스팅이 필요한 상황은 다음과 같다.

같은 클래스를 상속받는 두 파생클래스가 같은 기능의 함수에 매개변수로 들어가야 한다면, 굳이 함수를 따로 두개로 만들지 않고 매개변수로 업캐스팅 후 함수 안에서 다운캐스팅한다.

class Comparable{
public:
    virtual bool operator > (Comparable& op2) = 0;
    virtual bool operator < (Comparable& op2) = 0;
    virtual bool operator == (Comparable& op2) = 0;
};

class Circle : public Comparable{
    int radius;
public:
    Circle(int radius=1) { this->radius = radius; }
    int getRadius(){ return radius; }
    bool operator > (Comparable& op2);
    bool operator < (Comparable& op2);
    bool operator == (Comparable& op2);
};

bool Circle::operator > (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius > pc->getRadius()) return true;
    else return false;
}

위의 코드에서 순수 가상 연산자 함수의 매개변수의 데이터타입은 기본클래스다. 파생클래스 Circle에서 해당 함수를 구체화 하기 위해서 다시 다운캐스팅하고, 파생클래스의 멤버변수로 접근해서 기능을 작성한다. 이처럼 공통된 함수를 같이 쓰기 위해서 업다운 캐스팅 작업이 필요하다.

 

아래는 전체 코드이다.

#include <iostream>
using namespace std;


class Comparable{
public:
    virtual bool operator > (Comparable& op2) = 0;
    virtual bool operator < (Comparable& op2) = 0;
    virtual bool operator == (Comparable& op2) = 0;
};

class Circle : public Comparable{
    int radius;
public:
    Circle(int radius=1) { this->radius = radius; }
    int getRadius(){ return radius; }
    bool operator > (Comparable& op2);
    bool operator < (Comparable& op2);
    bool operator == (Comparable& op2);
};

bool Circle::operator > (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius > pc->getRadius()) return true;
    else return false;
}

bool Circle::operator < (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius < pc->getRadius()) return true;
    else return false;
}

bool Circle::operator == (Comparable& op2){
    Circle * pc;
    pc = (Circle *)&op2; // down casting
    if(this->radius == pc->getRadius()) return true;
    else return false;
}

template <class T>
T bigger(T a, T b){
    if(a > b) return a;
    else return b;
}

int main(){
    int a = 20,  b = 50, c;
    c = bigger(a, b);
    cout << "Which one is bigger 20 and 50 ? " << c << endl;
    /* These instances will be up casting to be parameter */
    Circle waffle(10), pizza(20), y;
    y = bigger(waffle, pizza); // Shoule be intger value
    cout << "The radius which has bigger radius waffle and pizza is " << y.getRadius() << endl;
}

/*
Which one is bigger 20 and 50 ? 50
The radius which has bigger radius waffle and pizza is 20
*/

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

c++에서 vector에 접근하는 4가지 방법  (0) 2024.01.21
inline function defined in source file? or header file?  (0) 2024.01.20
try-throw-catch  (1) 2024.01.20
while(cin >> x)  (0) 2024.01.20
switch-case  (0) 2022.06.11

+ Recent posts