给定一个基类作为参数,如果传递了一个派生类的特征,如何使用 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?
这是家庭作业
我有一个基类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;
}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何委托派生类使用其父构造函数?
- 呼叫运营商<<临时
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 在 C++ 中用派生类型重写成员函数
- 具有多个类、派生类的C++正向声明
- <<操作员在下面的行中工作
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?