![](/img/trans.png)
[英]Visual Studio Community 2015 Installation (Visual C++)
[英]this code compiles but doesnt show output when it runs (c++) in visual studio 2015 community
#include <conio.h> // include conio.h file
#include <iostream.h> // or #include<iostream>
int main()
{
int cout = 5;
cout << cout;
return 0;
}
为什么会这样?
代码正确编译但在运行时没有给出预期的输出
这不会给出输出5和所有其他东西
它也没有发出警告。
以下行声明了一个恰好被称为cout
的int
(它不是std::cout
流)
int cout = 5;
<<
运算符执行位移。
所以
cout << cout;
仅执行一次移位而不存储结果。
澄清一下,看看下面的程序:
#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;
}
它将输出:
cout's value is 5, and the result of the bit shift is 160
幕后发生的事情是, operator<<
已被超载以在左侧进行ostream
。
通过包含iostream
您将获得此函数,如果<<
运算符左侧有一个ostream
,编译器将知道您的意思。
没有库, <<
只是一个简单的移位运算符 。
另请注意,如果您不明智地包含using namespace std;
或者using std::cout
然后cout
将意味着ostream
和<<
将触发对库operator<<
function的调用。 如果在添加上面的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;
}
你命名你的变量cout
,你很困惑std::cout
。 您的示例执行位移操作 。 试试这个:
int main()
{
int cout = 5;
std::cout << cout;
return 0;
}
更好的是,将您的变量命名为其他内容以避免混淆:
int main()
{
int foo = 5;
std::cout << foo;
return 0;
}
如果没有显式声明std
命名空间,可以using namespace std;
在你的代码中或调用std::cout
然后cout
解析为main()
函数中的局部变量cout
。
即使你确实 using namespace std;
声明using namespace std;
cout
仍然会解析为局部变量 - 这就是为什么很多人,书籍和教程会建议您显式编写std::whatever
而不是使用命名空间的原因之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.