此代码编译但在Visual Studio 2015社区中运行(c ++)时不显示输出

Dhr*_*han 2 c++

#include <conio.h>  // include conio.h file
#include <iostream.h> // or #include<iostream>

int main()
{
    int cout = 5;   
    cout << cout;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

代码正确编译但在运行时没有给出预期的输出

这不会给出输出5和所有其他东西

它也没有发出警告.

wal*_*lly 9

以下行声明int恰好被调用cout(它不是std::cout流)

int cout = 5;
Run Code Online (Sandbox Code Playgroud)

<<运营商peforms有点转变.

所以

cout << cout;
Run Code Online (Sandbox Code Playgroud)

仅执行一次移位而不存储结果.


澄清一下,看看下面的程序:

#include<iostream>

int main()
{
    int cout = 5;
    auto shiftedval = cout << cout;
    std::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它将输出:

cout's value is 5, and the result of the bit shift is 160
Run Code Online (Sandbox Code Playgroud)

幕后发生的事情是,operator<< 已经超载以占据ostream左侧.

通过包含iostream你得到这个函数,编译器将知道你的意思,如果你有一个ostream<<运算符的左边.

如果没有库,<<那只会是一个按位移位运算符.


还要注意的是,如果你有不良深思熟虑包含using namespace std;using std::coutcout那么将意味着ostream<<将触发到库的调用operator<<函数.如果在添加using上面的声明之后包含cout新声明的名称的另一个声明将隐藏先前的声明,cout现在将int再次被视为一个声明,我们将回到正在使用的位移运算符功能.

例:

#include<iostream>

using namespace std; // using std:: at global scope

int main()
{
    int cout = 5;
    auto shiftedval = cout << cout;

    //the following will not compile, cout is an int:
    cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    //but we can get the cout from the global scope and the following will compile
    ::cout << "cout's value is " << cout << ", and the result of the bit shift is " << shiftedval << '\n';

    return 0;
}
Run Code Online (Sandbox Code Playgroud)