2013-10-21 2 views
1
class Player 
{ 

protected: 

    string type; 
    int rank; 

public: 

    virtual void printType() 
    { 
     cout<<"Calling Class Player, type is: general Player"<<endl; 
    } 

}; 


//class FootballPlayer: Derived from Player 

class FootballPlayer: public Player 
{ 

protected: 

public: 

    virtual void printRank() 
    { 
    cout<<"Calling Class FootballPlayer, Rank is: Football Player rank"<<endl; 

    } 

    void printType() 
    { 
    cout<<"Calling Class FootballPlayer, type is: Football Player"<<endl; 
    } 
}; 

class MaleFootballPlayer: public FootballPlayer 
{ 
public: 

    void printType() 
    { 
    cout<<"Calling Class MaleFootballPlayer, type is: Male Football Player"<<endl; 
    } 


    void printRank() 
    { 
    cout<<"Calling Class MaleFootballPlayer, Rank is: Male Player rank"<<endl; 

    } 

}; 

//class CricketPlayer: Derived from Player 

class CricketPlayer: public Player 
{ 

protected: 

public: 

    void printType() 
    { 
    cout<<"Calling Class CricketPlayer, type is: Cricket Player"<<endl; 
    } 
}; 


int main(int argc, const char * argv[]) 
{ 

    FootballPlayer fbplayer; 
    CricketPlayer crplayer; 
    MaleFootballPlayer malefbplayer; 


    FootballPlayer *fbplayerPtr; 
    fbplayerPtr=&malefbplayer; 
    fbplayerPtr->printType(); 


    return 0; 
} 

내가 프로그램을 실행, 나는이 얻을 출력,다단계 상속 및 다형성

클래스 MaleFootballPlayer를 호출, 유형 : 남자 축구 선수

나는 기본 클래스 포인터 (footballplayer)을 생성하고 파생 클래스 객체 (malefootballplayer)에 할당하면 기본 클래스에 속하는 함수를 호출해야하며 (가상으로 만들어지지 않으므로) 출력은 'FootBallPlayer, type is : Football Player'클래스를 호출해야합니다.

내 개념을 지우고 싶습니다.

감사합니다.

+0

'Player :: printType' _is_'virtual'을 선언했습니다. –

답변

0

MaleFootballPlayer 객체의 주소는 FootballPlayer 유형 포인터에 포함되어 있으며 기본 구현에서 virtual로 선언 된 printType() 메서드이므로 파생 클래스 인 MaleFootballPlayer 함수에 의해 재정의됩니다. 그게 왜 일어난거야. 가상 테이블에는 두 클래스의 printType() 함수에 대한 포인터가 들어 있지만 런타임에는 파생 클래스 printType() 함수 포인터가 선택되었습니다.

+0

'virtual'은 파생 클래스에서 반복되지 않기 때문에 사라지지 않습니다. – arne

+0

@ arne, 파생 클래스에서 "가상"키워드가 반복되는 경우 어떻게해야합니까? – Subhajit

+0

모두 같습니다. 함수가 모든 기본 클래스에서'virtual'으로 선언되면'virtual' 키워드가 반복되는지 여부에 관계없이 모든 파생 클래스에 대해 가상입니다. C++ 11은 함수를 오버로드하지 못하도록 구현자를 막을 수있는 final 키워드를 제공하지만 여전히 파생 된 구현은 기본 클래스 포인터 또는 참조에서 호출됩니다. – arne