如何使派生类的流式处理运算符也输出基类

How to make the streaming operator of the derived class also output the base class

本文关键字:运算符 处理 输出 基类 何使 派生      更新时间:2023-10-16

假设我有一个名为 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,因为您始终知道DogsShepherd的基类。只需使用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;
}

这是一个魔杖盒链接。