给定一个基类作为参数,如果传递了一个派生类的特征,如何使用 op<< 重载来打印派生类的特征?

Given a base class as a parameter, how do I use op<< overload to print the characteristics of a derived class if one is passed?

本文关键字:派生 lt 一个 特征 何使用 重载 打印 op 基类 参数 如果      更新时间:2023-10-16

这是家庭作业

我有一个基类Item和派生类Book。

我有op<<重载Item类:

ostream& operator<<(ostream& out, const Item* const item)
{
    out << item->getName() << endl;
    return out;
}

以及Book类:

ostream& operator<<(ostream& out, const Book* const b)
{
    out << b->getPages() << endl;
    return out;
}

然而,当我运行我的代码时,只使用Item操作符,它不打印一本书的页数。我已经确保打印的是"book",而不仅仅是基类。从我读过的材料来看,似乎重载基类和派生类的操作符是你应该做的,所以我不确定为什么我的图书信息没有打印出来。

您可以使用多态性来代替重载:为类添加一个虚拟打印方法:

class Item
{
 public:
  virtual void print(std::ostream& o) const
  {
    out << getName() << endl;
  }
 ....
};
class Book : public Item
{
 public:
  virtual void print(std::ostream& o) const
  {
    out << getPages() << endl;
  }
 ....
};

则使用单个ostream& operator<<:

ostream& operator<<(ostream& out, const Item& item)
{
    item.print(out);
    return out;
}
然后

Item* i1 = new Item(....);
Item* i2 = new Book(....);
std::cout << *i1 << " " << *i2 << std::endl;
delete i1;
delete i2;

如果您更改了派生类函数的签名,它将不再是基类成员函数的重写。

"然而只有Item操作符在我运行代码时使用" -这种行为可能是因为您将应用于指针*/引用&在基类;

如果你有一个容器,你想在其中存储从同一个基类派生的不同类的实例,并对它们应用operator<<,哪种行为将取决于每个被调用的实例的类,你必须确保:

1。在您的基类中至少有一个虚方法(这将导致编译器生成操作符dynamic_cast)
可以使用该类的虚表和以后的这个表2. 在您的项目中启用RTTI(运行时类型标识):project/c++/language启用RTTI支持3.使用以下思想实现operator<<:

ostream& operator<<(ostream& out, const Item& item)
{
    if (Book* pBook = dynamic_cast<Book*>(&item)
    {
        out << pBook ->getName() << endl;
    }
    if (OtherDerivedClassName* pOtherDerivedClass = dynamic_cast<OtherDerivedClassName*>(&item)
    {
// do other interesting things
    }
    return out;
}