我有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;
提前谢谢。
重载operator <<
在编译时根据参数的静态类型选择。因为tt
的静态类型是team
,所以它是operator <<
使用的。
如果希望对象的动态类型确定输出,则必须使用其他一些技术。例如,您可以让team
包含一个虚拟print
函数,并在BasketTeam
中覆盖它。然后,让一个人operator <<
team& t
,并打电话给t.print()
左右。这将根据t
的动态类型调用print
方法,这就是您正在寻找的。