반응형

Upcasting #1

  • 기반 클래스의 포인터로 파생 클래스를 가리킬 수는 있지만 파생 클래스의 고유한 멤버에 접근은 불가
  • 파생 클래스의 고유 멤버에 접근 하려면 기반 클래스 포인터를 파생 클래스의 포인터 타입으로 캐스팅 해야함
#include <iostream>
#include <string>

class Animal
{
public:
    int age;
    std::string name;
};

class Dog : public Animal
{
public:
    int color;
    int getColor() const { return color; }
};

int main()
{
    Dog dog; // 객체의 포인터 크기, 32bit : 4byte, // 64bit : 64bit

    //int* p = &dog; // error, 서로다른 타입, reinterpret_cast
    Animal* p = &dog; // ok.. 기반 클래스가 -> 파생 클래스를 가르키는 방법
    p->age = 20; // 기반 클래스 멤버
    p->name = "AA"; // 기반 클래스 멤버
    p->color = 1; // 파생 클래스 멤버(error)
    p->getColor(); // 파생 클래스 멤버(error)
    static_cast<Dog*>(p)->color = 10; // 파생 클래스 멤버에 접근을 위해서는 static_cast 필요
}

Upcasting #2

  • 동종(동일한 기반 클래스를 사용하는 클래스)을 처리하는 함수를 만들 수 있음
#include <iostream>
#include <string>

class Animal
{
public:
    int age;
};

class Cat : public Animal {};
class Dog : public Animal {};

void HappyNewYear(Animal* p) // Upcasting이 없으면 Cat*, Dog*... 등의 각 동물별 함수 필요
{
    ++(p->age);
}

int main()
{
    Dog dog;
    HappyNewYear(&dog);

    Cat cat;
    HappyNewYear(&cat);
}
  • 동종을 보관하는 컨테이너를 만들 수 있음
#include <vector>

class Animal
{
public:
    int age;
};

class Cat : public Animal {};
class Dog : public Animal {};

int main()
{
    std::vector<Dog*> v1; // Dog만 보관
    std::vector<Cat*> v2; // Cat만 보관
    std::vector<Animal*> v3; // 모든 동물 보관
}

예제(Composite 패턴)

  • 윈도우 탐색기
    • Folder는 File, Folder를 함께 보관
      • File, Folder는 공통의 기반 클래스가 필요
        • folder : item
        • file : item
      • A, B를 함께 보관하고 싶다면 공통의 기반 클래스가 필요
  • 파워포인트
    • Component
      • Group : Component
      • Shape : Component
        • Rect : Shape
        • Circle : Shape
반응형

'프로그래밍 언어 > C++' 카테고리의 다른 글

C++ 상속 예제(Polymorphism)  (0) 2019.05.12
C++ 오버라이드, 가상함수(Override & Virtual Function)  (0) 2019.05.12
C++ 상속(Inheritance)  (0) 2019.05.12
C++ STL 정리  (0) 2019.05.12
C++ STL 정책(Policy Base)  (0) 2019.05.12

+ Recent posts