什么是<<运算符在C ++? [英] What is the << operator for in C++?

查看:151
本文介绍了什么是<<运算符在C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从一个C#和Java背景来到C ++,我试图理解>> & < <$ / code>运算符,例如

I come from a C# and Java background into C++ and I'm trying to get to understand the >> & << operators such as in

std::cout << "Hello World";

这里不能理解的是< 运算符。我尝试声明我自己的简单函数,它总是返回整数 5 ,我可以像C#中一样调用它,

What I can't understand in here is what the << operator is for. I tried declaring my own simple function that always returns the integer 5 and I can call it as I did in C#,

int x = MyFunction();

并将 x 变更为 5 ,但为什么我需要使用 std :: cout << ?如果你帮助我理解>> <<

and that turns x into 5, but why do I need to use std::cout with <<? Also I would really appreciate it if you helped me understand what both >> and << are for.

感谢大家帮助我理解这一点。实际打开我的心是事实std :: cout是和对象:)

Thanks to all of you for helping me understand this. What actually opened my mind is the fact that std::cout is and object :)

推荐答案

但我相信你的困惑是你认为 std :: cout 是一个函数,你想知道为什么你不像这样调用它:

You didn't spell it out exactly, but I believe that your confusion is that you think that std::cout is a function, and you're wondering why you don't just call it like this:

std::cout("Hello World");

好吧, std :: cout 一个函数。此语句中的函数为 operator

Well, std::cout is not a function. The function in this statement is operator<<.

std::cout << "Hello World";

或者,更具体地说,函数是 std :: ostream :: operator< ;<(const char *)

Or, more specifically, the function is std::ostream::operator<<(const char*).

你需要理解的是,操作符只是函数, 运算符<< 作为 std :: ostream 的成员函数和 std :: cout std :: ostream 的对象。因此:

The thing you need to understand is that operators are just functions with an alternative calling syntax. operator<< is overloaded as a member function of std::ostream, and std::cout is an object of std::ostream. So this:

std::cout << "Hello World";

是另一种调用方法:

std::cout.operator<<("Hello World");

请注意,运算符<< 二元运算符,这意味着它需要两个参数,如果它被声明为一个自由函数,一个参数,如果它被声明为成员函数。当使用替代调用语法时,左侧的对象是第一个参数,右侧的对象是第二个参数。在声明为成员函数的情况下,如在这种情况下,左边的对象是调用对象,右边的对象是参数。

Note that operator<< is a binary operator, which means it takes two arguments, if it's declared as a free function, and one argument if it is declared as a member function. When you use the alternative calling syntax, the object on the left is the first argument, and the object on the right is the second argument. In the case where it is declared as a member function, as it is in this case, the object on the left is the calling object, and the object on the right is the argument.

如果它被声明为一个自由函数,它会是什么样子:

Here's what it would look like if it were declared as a free function:

operator<<(std::cout, "Hello World");

但是,无论是声明为成员还是自由函数,调用语法。

But, whether it is declared as a member or a free function, you can still use the same alternative calling syntax.

这篇关于什么是&lt;&lt;运算符在C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆