Dav*_*aiz 0 c++ inheritance abstract-class operator-overloading
我有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);
Run Code Online (Sandbox Code Playgroud)
这是输出运算符:
std:: ostream& operator<< (std :: ostream& out, team& T)
{
return (out<<T.team_name<<" "<<T.games_played);
}
Run Code Online (Sandbox Code Playgroud)
派生类:
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);
Run Code Online (Sandbox Code Playgroud)
这是派生类的输出运算符:
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;
}
Run Code Online (Sandbox Code Playgroud)
当我创建对象并尝试打印它时,我只能让基类看起来不是派生类.
team* tt = new BasketTeam ("ran");
cout<<*tt;
Run Code Online (Sandbox Code Playgroud)
提前致谢.
根据operator <<
参数的静态类型,在编译时选择重载.既然tt
是静态类型team
,那operator <<
就是它所使用的.
如果希望对象的动态类型确定输出,则必须使用其他一些技术.例如,您可以team
包含一个虚print
函数,并覆盖它BasketTeam
.然后,让一个operator <<
拿一个team& t
,然后打电话t.print()
.这将print
根据t
您要查找的动态类型调用该方法.