gpt4 book ai didi

c++ - 我应该什么时候返回 std::ostream?

转载 作者:太空宇宙 更新时间:2023-11-04 15:42:23 26 4
gpt4 key购买 nike

每次我要创建像 std::string 运算符这样的运算符来显示值(无运算符)时,我都会返回 std::ostream,但我不不知道为什么。如果 std::ofstream 用作函数成员运算符函数 (std::cout),我该如何返回它,我应该何时返回它以及为什么?

例子:

class MyClass
{
int val;
std::ostream& operator<<(const std::ostream& os, const MyClass variable)
{
os << variable.val;
}
}

std::string 上:

std::string a("This is an example.");
std::cout << a;

最佳答案

通常返回对 ostream 的引用重载时 << , 允许链接。这:

s << a << b;

等同于函数调用

operator<<(operator<<(s,a),b);

并且仅在内部调用返回合适的类型作为外部调用的参数时才有效。

要实现这一点,只需通过引用获取流参数,并通过引用直接返回相同的流:

std::ostream & operator<<(std::ostream & s, thing const & t) {
// stream something from `t` into `s`
return s;
}

或从其他一些重载返回:

std::ostream & operator<<(std::ostream & s, thing const & t) {
return s << t.whatever();
}

关于c++ - 我应该什么时候返回 std::ostream?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21116750/

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