學習C++並且無法理解爲什麼我不能使用「std :: cin」作爲參數。爲什麼我不能使用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;
}
學習C++並且無法理解爲什麼我不能使用「std :: cin」作爲參數。爲什麼我不能使用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;
}
std::cin >> x
返回對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){ //...
)
你大概想通過x
。但cin >> x
的結果是cin
,而不是x
。
該解決方案易於
std::cin >> x;
std::cout << doubleNumber(x);
你不能真正通過cin
如果你真的想因爲它是一個流,而不是int
。
而返回類型>>
就是它讓std::cin >> x >> y >> z;
這樣的東西起作用的方式。
所以沒有辦法將cin >> x作爲參數傳遞,您在使用它作爲參數之前總是需要詢問? –
是的,這是正確的。 –
函數不能帶流類型的參數嗎? (只是問':)。 –
std::cin
是一個全局對象和operator >>
,您發出呼叫的是,再次返回std::cin
的方法,這樣你就可以寫的東西,如:
std::cin >> x >> y;
我想說的是,std::cin >> x
輸出不是你剛輸入的價值,就像你期望的那樣,但是它本身就是std::cin
。
有關詳細信息,請參閱http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt。
非常感謝你,那正是我一直在尋找的:) –