【问题标题】:Output operator (<<) for abstract class and derived class抽象类和派生类的输出运算符 (<<)
【发布时间】:2013-12-21 16:05:54
【问题描述】:

我有 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;

提前致谢。

【问题讨论】:

    标签: c++ inheritance operator-overloading abstract-class


    【解决方案1】:

    重载的operator &lt;&lt; 是在编译时根据参数的静态类型选择的。由于tt的静态类型是team,所以它使用的就是operator &lt;&lt;

    如果您希望对象的动态类型来确定输出,则必须使用其他一些技术。例如,您可以让team 包含一个虚拟的print 函数,并在BasketTeam 中覆盖它。然后,让一个operator &lt;&lt; 接一个team&amp; t,然后打电话给t.print() 左右。这将根据t 的动态类型调用print 方法,这就是您要查找的内容。

    【讨论】:

    • 谢谢,它有效!但是还有一个问题,输出应该是: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 的事情,省略括号,从而产生函数地址而不是返回值?
    • 这就是我正在做的事情:(out
    猜你喜欢
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2013-11-30
    • 2011-02-01
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    相关资源
    最近更新 更多