在cin中键入Casting(C++)

Adi*_*tya 0 c++ type-conversion

    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;
Run Code Online (Sandbox Code Playgroud)

上面的代码显示错误.为什么我可以在cout中输入,但不能在cin中输入?

小智 7

像这样的演员:

  float(x)
Run Code Online (Sandbox Code Playgroud)

生成一个无名的临时对象类型float.>>运算符实际上看起来像这样:

 istream & operator>>( istream &, float & f );
Run Code Online (Sandbox Code Playgroud)

并且您不能将非const引用绑定到临时.

输出运算符实际上看起来像这样:

 ostream & operator<<( ostream &, const float & f );
Run Code Online (Sandbox Code Playgroud)

并且你可以将const引用绑定到临时,所以这是有效的.