当我尝试使用 cout 时,它输出一个随机数而不是我想要的句子。没有编译错误,程序运行正常。
这是我的代码:
//question.h
#ifndef _QUESTION_H_
#define _QUESTION_H_
using namespace std;
int first()
{
cout<<"question \n";
return 0;
}
#endif
//main.cpp
#include <iostream>
#include "question.h"
using namespace std;
void main(){
cout<<""<<first<<""<<endl;
cin.ignore();
cin.get();
}
我对编写自己的头文件还很陌生,所以我不确定是我做错了什么还是 visual studio 有问题。
最佳答案
您正在打印函数的地址。你需要调用它:
cout<<""<<first()<<""<<endl;
^^
如评论中所述,这也不一定要输出您所期望的。函数参数的顺序(这只是一堆函数调用)是未指定的,因此您的函数输出可以位于编译器选择的任何位置。要解决此问题,请放置单独的语句:
cout<<"";
cout<<first(); //evaluated, so output inside first() printed before return value
cout<<""<<endl;
空字符串可能无关紧要,但当您将它们替换为可见的内容时,它会很重要。
此外,不要使用 void main
。使用 int main()
或 int main(int, char**)
( see here )。不要使用 using namespace std;
,尤其是在 header 中,因为 std
中有很多废话,这些废话会随该语句一起出现,从而导致容易和困惑的冲突(see here)。最后选择一个和identifiers reserved for the implementation不冲突的名字作为你的护卫。
关于c++ - cout奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15237705/