2017-04-07 142 views
0
int x; 

    cout << "Enter an integer :: " << endl; 
    cin >> x ; 
    cout << "Your value is = " << x << endl; 

    cout << "Enter a float :: " << endl; 
    cin >> float (x) ; 
    cout << "Your value is = " << x << endl; 

上面的代碼顯示錯誤。爲什麼我可以輸入cout而不是cin?cin類型鑄造(C++)

+0

cin需要一個l值引用,但是當您將其強制浮動時,它將成爲一個r值引用。 cout可以同時採用r和l值引用。 – user45681

+0

看起來你試圖用'x'來存儲'int'和'float'。 C++不能像那樣工作。 – chris

回答

7

甲投像這樣:

float(x) 

產生float類型的無名臨時對象。 >>操作有效地看起來是這樣的:

istream & operator>>(istream &, float & f); 

,你不能綁定一個非const引用到一個臨時的。

輸出操作有效地看起來是這樣的:

ostream & operator<<(ostream &, const float & f); 

,你可以綁定一個常量引用一個臨時的,所以此工程。