2013-12-21 49 views
0

我有2個類,抽象基類&派生類。 但由於某些原因,我無法適當地重載輸出操作符。抽象類和派生類的輸出運算符(<<)

這是基礎類:

class team 
{ 
    char* team_name; 
    int games_played; 

public: 
    team(const char* tname); 
    virtual ~team(); 
    virtual void update_lpoints(const int win_loss)=0; 
    friend std:: ostream& operator<< (std :: ostream& out, team& T);  
}; 

std:: ostream& operator<< (std :: ostream& out, team& T); 

這裏是輸出操作:

std:: ostream& operator<< (std :: ostream& out, team& T) 
{ 
    return (out<<T.team_name<<" "<<T.games_played); 
} 

派生類:

class BasketTeam : public team 
{ 
    int league_points; 
    int points_for; 
    int points_against; 

public: 
     BasketTeam(const char* tname); 
     ~BasketTeam(); 

     friend std:: ostream& operator<< (std :: ostream& out, BasketTeam& T); 
}; 

std:: ostream& operator<< (std :: ostream& out, BasketTeam& T); 

這裏是派生輸出操作等級:

std:: ostream& operator<< (std :: ostream& out, BasketTeam& T) 
{ 
    out<<T.get_name()<<" "<<T.get_played_games()<<" "<<T.league_points<<" "<<T.points_for<<" "<<T.points_against<<endl; 
    return out; 
} 

當我創建對象並嘗試打印它時,我只能讓基類看起來不是派生類。

team* tt = new BasketTeam ("ran"); 
cout<<*tt; 

在此先感謝。

回答

6

重載的operator <<是在編譯時根據參數的靜態類型選擇的。由於tt的靜態類型爲team,因此它使用的是operator <<

如果你想要動態類型的對象來確定輸出,你必須使用其他技術。例如,您可以讓team包含虛擬print函數,並在BasketTeam中覆蓋它。然後,有一個operator <<需要team& t,並且請撥打t.print()左右。這將根據t的動態類型調用print方法,這是您正在尋找的。

+0

謝謝,它的作品! 但是還有一個問題,輸出應該是: TEAM_NAME 0 0 0 0 但由於某種原因輸出: TEAM_NAME 00F9AC3E8 0 0 0 任何想法,爲什麼? 該變量是int並被初始化: games_played = 0; 但地址是輸出的地址。 –

+0

打印標題是: std :: ostream&print_info(std :: ostream&out) –

+0

我不能說沒有看到相關的代碼。你能否像'T.get_played_games'這樣做,省略小括號,這會產生函數地址而不是返回值? – eran