为什么我不能使用 std:cin 作为参数

Why can't i use std:cin as an argument

学习c++,不明白为什么不能用"std::cin"作为参数。

#include <iostream>
#include "stdafx.h"
int doubleNumber(int a)
{
    return 2 * a;
}

int main()
{
    int x;
    std::cout << doubleNumber(std::cin >> x);
    return 0;
}

你大概想通过 x。但是cin >> x的结果是cin,不是x.

解决方法很简单

 std::cin >> x;
 std::cout << doubleNumber(x);

如果你真的想传递 cin,你实际上不能传递,因为它是一个流,而不是 int

并且 >> 的 return 类型是为了让 std::cin >> x >> y >> z; 之类的东西起作用的方式。

std::cin 是一个全局对象,而你调用的 operator >> 是一个 returns std::cin 的方法,所以你可以这样写:

std::cin >> x >> y;

我想说的是 std::cin >> x 的输出不是您刚刚输入的值,正如您所期望的那样,而是 std::cin 本身。

有关详细信息,请参阅 http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt

std::cin >> x returns 对 cin 的引用,它不能隐式转换为 int.

您可以像这样使用 , 运算符:

(std::cin >> x, x)

首先 运行 std::cin >> x 然后将该表达式计算为 x.

#include <iostream>
int doubleNumber(int a)
{
    return 2 * a;
}

int main()
{
    int x;
    std::cout << doubleNumber( (std::cin >> x, x) );
    return 0;
}

不过,将它分成两行可能会使它更具可读性。

在任何情况下,std::cin >> x 都可以用作表达式。 例如,将流隐式转换为布尔值以检查它们是否处于成功(良好)状态是很常见的。 (例如,if(std::cin >> x){ //...