cout奇怪的输出

Bra*_*ard 1 c++ visual-studio-2010

当我尝试使用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();
}
Run Code Online (Sandbox Code Playgroud)

我很自然地编写自己的头文件,所以我不确定我是否做错了或者是否存在visual studio的问题.

chr*_*ris 5

您正在打印该功能的地址.你需要打电话给它:

cout<<""<<first()<<""<<endl;
               ^^
Run Code Online (Sandbox Code Playgroud)

正如评论中所提到的,这也不必输出您期望的结果.函数的参数(也就是一堆函数调用)的顺序是未指定的,因此您的函数输出可以位于编译器选择的任何位置.要解决此问题,请单独声明:

cout<<"";
cout<<first(); //evaluated, so output inside first() printed before return value
cout<<""<<endl;
Run Code Online (Sandbox Code Playgroud)

空字符串可能无关紧要,但是当你用可见的东西替换那些字符串时.

另外,不要使用void main.使用int main()int main(int, char**)(见这里).不要使用using namespace std;,尤其是在标题中,因为std它中包含很多废话,并且会引入容易和混乱的冲突(参见此处).最后,选择一个与为实现保留的标识符不冲突的名称作为包含保护.