gpt4 book ai didi

c++ - 在没有 static_cast<> 的派生类中重载 std::ostream& operator<<

转载 作者:太空狗 更新时间:2023-10-29 23:31:01 24 4
gpt4 key购买 nike

这是重载 ostream& operator<< 的唯一方法吗?对于派生类而不复制基类的代码? Actor 不是要避免的东西吗?

除了在基类中定义某种函数将基类的数据表示为 std::operator<< 可以“吃掉”的东西(如字符串?),对派生类做同样的事情(当然是在派生类流中调用基类流表示函数。rep.函数)。

这个问题的理想解决方案是什么?

#include <iostream>

class Base
{
private:
int b_;
public:
Base()
:
b_()
{};

Base (int b)
:
b_(b)
{};

friend std::ostream& operator<<(std::ostream& os, const Base& b);
};

std::ostream& operator<< (std::ostream& os, const Base& b)
{
os << b.b_;
return os;
}

class Derived
:
public Base
{
private:
int d_;
public:
Derived()
:
d_()
{};

Derived (int b, int d)
:
Base(b),
d_(d)
{};

friend std::ostream& operator<<(std::ostream& os, const Derived& b);
};

std::ostream& operator<< (std::ostream& os, const Derived& b)
{
os << static_cast<const Base&>(b) << " " << b.d_;
return os;
}



using namespace std;


int main(int argc, const char *argv[])
{
Base b(4);

cout << b << endl;

Derived d(4,5);

cout << d << endl;

return 0;
}

最佳答案

嗯……如果在结果未正确定义的上下文中进行转换,则应避免转换,但转换为基数始终是安全的。

考虑到派生引用退化为基引用,可以避免显式转换,因此您可以使用隐式转换,就像在这种情况下:

std::ostream& operator<< (std::ostream& os, const Derived& b)
{
const Base& bs = b;
os << bs << " " << b.d_;
return os;
}

关于c++ - 在没有 static_cast<> 的派生类中重载 std::ostream& operator<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10725772/

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