C ++ - 派生类中的重载运算符不起作用

时间:2013-12-09 18:20:34

标签: c++ class friend derived-class

好的,因此派生类的重载运算符不起作用。它只在基类中使用重载运算符。有什么想法吗?

类定义头文件中的基类运算符:

friend ostream & operator << (ostream & out, const PocketMonster & p);

基类操作符:

ostream & operator << (ostream & out, const PocketMonster & p)
{
    out << endl << "(Monster Types: Type 1 = Fire, Type 2 = Water, Type 3 = Grass)" << endl 
    << "PocketMonster Information: " << endl << "Name: " << p.name << endl
    << "Status (0=Dead, 1=Alive): " << p.status << endl << "Level: " << p.level << endl 
    << "Strength: " << p.strength << endl
    <<  endl << "(Weapon Types: 1 = Fire, 2 = Water, 3 = Grass, 4 = Normal)" << endl
    << p.name << "'s Weapon Information: " << endl << "Weapon type: " << p.get_weaptype() << endl
    << "Weapon durability: " << p.get_weapdura() << endl << "Weapon level required: " << p.get_weaplvl() << endl << endl;
    return out;
}

类定义头文件中的派生类重载运算符:

friend ostream & operator << (ostream & out, const FireMonster & p);

派生类重载运算符:

ostream & operator << (ostream & out, const FireMonster & p)
{
    return out << static_cast<const PocketMonster&>(p) << endl << "FireMonster Attributes:" << endl << "Temperature: " << p.temperature << endl;

}

这是一个尝试输出信息的函数

void displayLosers(vector<PocketMonster *> p)
{
    for (int i=0; i<p.size(); i++)
    {
        if (p[i]->get_status() == false)
        {
            cout << p[i]->get_name() << " is a loser." << endl;
            cout << *(p[i]);
        }

    }
}

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

将虚函数Output添加到基类(在公共或受保护的部分):

virtual ostream & Output (ostream & out) const;

// ...

ostream & PocketMonster::Output (ostream & out) const
{
    out << endl << "(Monster Types: Type 1 = Fire, Type 2 = Water, Type 3 = Grass)" << endl 
    << "PocketMonster Information: " << endl << "Name: " << p.name << endl
    << "Status (0=Dead, 1=Alive): " << p.status << endl << "Level: " << p.level << endl 
    << "Strength: " << p.strength << endl
    <<  endl << "(Weapon Types: 1 = Fire, 2 = Water, 3 = Grass, 4 = Normal)" << endl
    << p.name << "'s Weapon Information: " << endl << "Weapon type: " << p.get_weaptype() << endl
    << "Weapon durability: " << p.get_weapdura() << endl << "Weapon level required: " << p.get_weaplvl() << endl << endl;
    return out;
}

并在派生类中覆盖它:

virtual ostream & Output (ostream & out) const;

// ...

ostream & FireMonster::Output (ostream & out) const
{
    return out << PocketMonster::Output(out) << endl << "FireMonster Attributes:" << endl << "Temperature: " << p.temperature << endl;
}

然后按以下方式为基类重写operator<<

ostream & operator << (ostream & out, const PocketMonster & p)
{
    return p.Output(out);
}

并删除operator<<派生类。