如何使派生类的流式处理运算符也输出基类
How to make the streaming operator of the derived class also output the base class
假设我有一个名为 dogs 的类并从中继承了一个名为 shepherd 的类,现在我为我的基类重载了流运算符,但现在当我重载派生类的流运算符时,我希望它也输出最初来自我的基类的变量。
显然,我可以复制粘贴用于重载基类流运算符的代码,但我正在寻找一种更优雅的解决方案,该解决方案不涉及复制大量代码(特别是因为实际示例在基类中具有更多变量)。
举个例子。
class Dogs
{
public:
int N_legs;
bool hair_short;
};
class Shepherd : public Dogs
{
public:
bool guarding;
};
std::ostream &operator<<(std::ostream &os, Dogs dogs)
{
os << "the content of class dogs" << std::endl;
os << dogs.N_legs << "t" << dogs.hair_short << std::endl;
return os;
}
现在我尝试了动态演员表,但没有奏效。
std::ostream &operator<<(std::ostream &os, Shepherd shepherd)
{
os << dynamic_cast<Dogs>(shepherd);
os << "The content of class shepherd" << std::endl;
os << shepherd.guarding << std::endl;
return os;
};
在主楼的某个地方
Dogs dogs;
dogs.N_legs = 4;
dogs.hair_short = true;
std::cout << dogs << std::endl;
Shepherd shepherd;
shepherd.N_legs = 4;
shepherd.guarding = true;
std::cout << shepherd << std::endl;
现在这将给我一个仅包含派生类变量的输出(当您注释掉动态强制转换时),但我也希望拥有基类的内容。
dyanamic_cast仅适用于引用和指针,这就是您的代码无法编译的原因。您应该将参数类型更改为const &
,不仅是为了修复错误,也是为了避免不必要的复制。
std::ostream &operator<<(std::ostream &os, const Dogs& dogs)
std::ostream &operator<<(std::ostream &os, const Shepherd& shepherd)
{
os << dynamic_cast<const Dogs&>(shepherd);
...
顺便说一句:对于这种情况,static_cast
就足够了。
这里不需要dynamic_cast
,因为您始终知道Dogs
是Shepherd
的基类。只需使用static_cast
:
std::ostream &operator<<(std::ostream &os, const Shepherd& shepherd)
{
os << static_cast<const Dogs&>(sheperd);
os << "The content of class shepherd" << std::endl;
os << shepherd.guarding << std::endl;
return os;
};
改用static_cast
;你在编译时知道基类型!
std::ostream &operator<<(std::ostream &os, Shepherd shepherd) {
os << static_cast<Dogs>(shepherd);
os << "The content of class shepherd" << std::endl;
os << shepherd.guarding << std::endl;
return os;
}
这是一个魔杖盒链接。
相关文章:
- 余数运算符的等效操作,用于处理低于允许的最小值
- 如何处理运算符=中的常量成员?
- 如何处理自定义输出运算符中的 iomanips?
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- RPN计算器c++错误处理和多个运算符
- 在C++中,一元减号运算符如何处理整数文本
- delete运算符如何处理c中的指针
- 处理输入流运算符>>中的无效输入
- 单独的处理程序左值和右值 [] 运算符
- 运算符重载时未处理<<异常
- C++自定义控制台类 - 如何处理运算符未重载"<<"的对象?
- std::string 的转换运算符无法处理赋值
- 在三元字符串中处理一元NOT运算符的调车场算法
- c++是否需要在用户定义和类特定的删除运算符中处理nullptr
- 处理类和赋值运算符
- 文件处理 - 错误:与 while 循环 (C++) 中的"运算符>>"不匹配(代码::块)
- 编译器在遇到提取或插入运算符时处理信息(字符串、操纵器等)的顺序是什么?
- 如何使派生类的流式处理运算符也输出基类
- 为什么我的运算符重载处理左对象与右对象
- 为什么同时使用一个赋值运算符处理复制和移动赋值效率不高