C++ 16.메소드의 다형성

-메소드의 다형성

 

#include <iostream>

#include <string>

using namespace std;

 

class Musician

{

        string name;

public:

        Musician(string name)

        {

               this->name = name;

        }

        virtual void Play()

        {

               cout<<name<<"연주하다."<<endl;

        }

   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;

        }

};

 

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)

{

        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->Play();

}

 

void StartConcert(Musician &musician)

{

        musician.Introduce();

        musician.Play();

}

 

728x90

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

C++ 18. 무효화  (0) 2016.04.19
C++ 17. 형식의 다형성  (0) 2016.04.19
C++ 15.다중 상속  (0) 2016.04.19
C++ 14.상속 일반화 개요  (0) 2016.04.19
C++ 13.C++에서의 형변환  (0) 2016.04.19

이 글을 공유하기

댓글

Designed by JB FACTORY