我想知道流类在 C++ 中是如何工作的。当你说:
cout<<"Hello\n";
“<<”究竟是做什么的。我知道 cout 是一个对象形式的 iostream,表示面向窄字符 (char) 的标准输出流。
在 C 中,“<<”是位移运算符,因此它将位向左移动,但在 C++ 中,它是和插入运算符。好吧,这就是我所知道的,我真的不明白它是如何工作的。
我要的是关于 C++ 中的流类的详细解释,以及它们是如何定义和实现的。
非常感谢您的宝贵时间,抱歉我的英语不好。
最佳答案
让我们创建一个类似于 cout
的类(但没有那么多花里胡哨的东西)。
#include <string>
class os_t {
public:
os_t & operator<<(std::string const & s) {
printf("%s", s.c_str());
return *this;
}
};
int main() {
os_t os;
os << "hello\n";
os << "chaining " << "works too." << "\n";
}
注意事项:
-
operator<<
是运算符重载,就像operator+
或所有其他运营商。 - 链接起作用是因为我们返回了自己:
return *this;
.
如果你不能改变os_t
怎么办? class 因为是别人写的?
我们不必使用成员函数来定义此功能。我们也可以使用自由函数。让我们也证明一下:
#include <string>
class os_t {
public:
os_t & operator<<(std::string const & s) {
printf("%s", s.c_str());
return *this;
}
};
os_t & operator<<(os_t & os, int x) {
printf("%d", x);
return os;
// We could also have used the class's functionality to do this:
// os << std::to_string(x);
// return os;
}
int main() {
os_t os;
os << "now we can also print integers: " << 3 << "\n";
}
运算符重载还有什么用处?
在 GMP 库中可以找到一个很好的例子来说明这种逻辑是如何有用的。该库旨在允许任意大的整数。我们通过使用自定义类来做到这一点。下面是它的使用示例。请注意,运算符重载让我们编写的代码看起来几乎与我们使用传统的 int
相同。类型。
#include <iostream>
#include <gmpxx.h>
int main() {
mpz_class x("7612058254738945");
mpz_class y("9263591128439081");
x = x + y * y;
y = x << 2;
std::cout << x + y << std::endl;
}
关于c++ - C++ 流是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23253153/