C++ 19.하향 캐스팅

-하향 캐스팅

#include <iostream>

#include <string>

using namespace std;

 

class Musician

{

        string name;

public:

        Musician(string name)

        {

               this->name = name;

        }

        virtual void Play() = 0; //순수 가상 메소드(추상 클래스)(기능 구현을위한 약속 메소드)

        void Introduce()

        {

               cout<<name<<"음악가 : 안녕"<<endl;

        }

        string GetName()const

        {

               return name;

        }

};

 

class Pianist:public Musician

{

public:

        Pianist(string name):Musician(name)

        {

        }

        virtual void Play()

        {

        cout<<GetName()<<"연주하다."<<endl;

        cout<<"딩동댕♩♪♬"<<endl;

        }

        void Tuning()

        {

               cout<<GetName()<<"조율하다"<<endl;

               cout<<"도도 레레 미미 파파"<<endl;

        }

};

 

class Drummer:public Musician

{

public:

        Drummer(string name):Musician(name)

        {

        }

        virtual void Play()

        {

        cout<<GetName()<<"연주하다"<<endl;

        cout<<"두두둥~~~"<<endl;

        }

};

 

void StartConcert(Musician *musician);

void StartConcert(Musician &musician);

 

int main(void)

{

        /*Musician *mu = new Musician("홍길동");

        delete mu;*/

        Pianist *pianist1 = new Pianist("피아노맨1");

        Drummer *drummer1 = new Drummer("두둥맨1");

        StartConcert(pianist1);

        StartConcert(drummer1);

        delete pianist1;

        delete drummer1;

 

        cout<<"==============================="<<endl;

 

        Pianist pianist2("피아노맨2");

        Drummer drummer2("두둥맨2");

        StartConcert(pianist2);

        StartConcert(drummer2);

        return 0;

}

 

void StartConcert(Musician *musician)

{

        musician->Introduce();

        //실행 시간에 musician Pianist인지 확인하여 하향 캐스팅

        //만약 피아니스트가 아니면 캐스팅 실패하고 0 반환함

        //Pianist *pianist = (*Pianist)musician; //CPP에서는 강제 형변환을 사용하지 마세요

        Pianist *pianist = dynamic_cast<Pianist*>(musician);

        if(pianist)

        {

               pianist->Tuning();

        }

        musician->Play();

 

}

 

void StartConcert(Musician &musician)

{

        musician.Introduce();

        musician.Play();

}

 

 

728x90

'C++ > 설명' 카테고리의 다른 글

C++ 21.추상 클래스  (0) 2016.04.19
C++ 20. 인터페이스  (0) 2016.04.19
C++ 18. 무효화  (0) 2016.04.19
C++ 17. 형식의 다형성  (0) 2016.04.19
C++ 16.메소드의 다형성  (0) 2016.04.19

이 글을 공유하기

댓글

Designed by JB FACTORY