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;
在此先感謝。
謝謝,它的作品! 但是還有一個問題,輸出應該是: TEAM_NAME 0 0 0 0 但由於某種原因輸出: TEAM_NAME 00F9AC3E8 0 0 0 任何想法,爲什麼? 該變量是int並被初始化: games_played = 0; 但地址是輸出的地址。 –
打印標題是: std :: ostream&print_info(std :: ostream&out) –
我不能說沒有看到相關的代碼。你能否像'T.get_played_games'這樣做,省略小括號,這會產生函數地址而不是返回值? – eran