c++ - cout奇怪的输出

标签 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();
}

我对编写自己的头文件还很陌生,所以我不确定是我做错了什么还是 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/

相关文章:

c# - 找不到 wcf serviceActivations

c# - Reportviewer 报表过滤器 - 检查日期是否为空

c# - 结合 C++ 和 C#

c++ - 更好的事件处理机制?

c++ - 指向指针的指针和指向数组的指针

windows - 如何找出哪个库包含 libcmt?

visual-studio-2010 - 我失去了波浪状的红色下划线功能

C++ 为什么存在 "const volatile"类型限定符?

c++ - 析构函数中函数调用的段错误

c - Win32 console-only 应用程序,防止 "missing dll"对话框