5

In the example below, what exactally is the << operator doing? I'm guessing it is not a bitwise operator.

std::cout << "Mouse down @ " << event.getPos() << std::endl;

I understand what the code will do here: Use standard out, send this text, send an end of line. Just I've never come accross the use of this << apart from on raw binary.

I'm starting out with C++. And, as an operator of sorts, it's hard to search for a description of this and what it means. Can someone enlighten me and/or give me a pointer as to what to google for?

Thanks Ross

4

6 回答 6

11

答案是:<<运算符默认为整数类型进行左移,但它可以被重载以做任何你想做的事情!

在 C++ 发明者 Bjarne Stroustroup 的同名著作The C++ Programming Language中首次展示了这种用于将字符串传送到流中的语法(我认为)。个人觉得重新定义一个operator做IO是噱头;它使演示代码看起来很酷,但无助于使代码易于理解。运算符重载作为一种技术在编程语言社区中受到广泛批评。


编辑:因为还没有人提到这一点:

operator<<ostream类中定义,cout是一个实例。类定义位于iostream 库中,它是#include'd as <iostream>

于 2010-07-24T14:54:44.133 回答
3

operator<<正在超载。查看运算符重载

于 2010-07-24T14:51:28.397 回答
3

这有时被称为“流插入运算符”,这是最常见的用途:将数据插入流中。但是,有时我看到它在执行序列化之类的操作时将数据插入到其他对象中被重载。

于 2010-07-24T14:51:36.083 回答
3

像 c++ 中的任何运算符一样,<< 正在执行操作。使用重载,带有 ostream 左操作数(std::cout 是 ostream 类型),它被用作流运算符来打印各种类型的数据。例如,你可以做

int x = 10;
std::string y = " something";
std::cout << x << y << std::endl;

这将输出“10 个东西”。

在这种情况下,@ 不会被任何东西取代。operator<< 只是转储结果。

std::endl 不仅是行尾,它还将结果刷新到输出设备。

于 2010-07-24T14:58:48.257 回答
1

尝试编写一个程序,在其中创建一个对象并调用重载的 << 运算符,

class x {
    //declare some pvt variables
    //overload << operator
};

int main() {
    x obj;
    cout << obj;
}

通过这样做,您将了解使用以下语句背后的基本原理

cout << string_var << int_var;

您可以假设 'string' 和 'int' 为具有重载 << 运算符的类,即使不是真的。

于 2010-07-24T16:00:58.123 回答
-4

它是一个“按位左移”运算符。

n << p

移动 n 个左 p 个位置的位。零位被移入低位。3 << 2 是 12。

在问题的上下文中,它会将某些内容推送到“ cout ”中,这是当前的输出流。

于 2010-07-24T14:51:19.287 回答