gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 11:43:36 25 4
gpt4 key购买 nike

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

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

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]);
}

}
}

提前感谢您的帮助!

最佳答案

添加虚函数Output到基类(在公共(public)或 protected 部分):

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<<对于派生类。

关于C++ - 派生类中的重载运算符不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20477777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com