C++ #include<iostream> 存在,但出现错误:标识符“cout”未定义。为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13208547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:05:19  来源:igfitidea点击:

The #include<iostream> exists, but I get an error: identifier "cout" is undefined. Why?

c++visual-studiocomvisual-studio-2012

提问by Andrey Bushman

I learn C++ and COM through the books. In the IDE MS Visual Studio 2012 I have created new empty C++ project, and added some existing files to it. My CPP file contains #include<iostream>row, but in editor I got such messages:

我通过书籍学习 C++ 和 COM。在 IDE MS Visual Studio 2012 中,我创建了新的空 C++ 项目,并向其中添加了一些现有文件。我的 CPP 文件包含#include<iostream>行,但在编辑器中我收到了这样的消息:

Error: identifier "cout" is undefined

错误:标识符“cout”未定义

end

结尾

Error: identifier "endl" is undefined

错误:标识符“endl”未定义

Screen:

屏幕:

enter image description here

在此处输入图片说明

Why it happens?

为什么会发生?

回答by juanchopanza

You need to specify the std::namespace:

您需要指定std::命名空间:

std::cout << .... << std::endl;;

Alternatively, you can use a usingdirective:

或者,您可以使用using指令:

using std::cout;
using std::endl;

cout << .... << endl;

I should add that you should avoid these usingdirectives in headers, since code including these will also have the symbols brought into the global namespace. Restrict using directives to small scopes, for example

我应该补充一点,您应该避免using在头文件中使用这些指令,因为包含这些指令的代码也会将符号引入全局命名空间。例如,将 using 指令限制在小范围内

#include <iostream>

inline void foo()
{
  using std::cout;
  using std::endl;
  cout << "Hello world" << endl;
}

Here, the usingdirective only applies to the scope of foo().

在这里,该using指令仅适用于foo().

回答by arash

You can add this at the beginning after #include <iostream>:

您可以在以下开头添加此内容#include <iostream>

using namespace std;

回答by billz

coutis in std namespace, you shall use std::coutin your code. And you shall not add using namespace std;in your header file, it's bad to mix your code with std namespace, especially don't add it in header file.

cout在 std 命名空间中,您应std::cout在代码中使用。并且您不应using namespace std;在头文件中添加,将代码与 std 命名空间混合是不好的,尤其是不要将其添加到头文件中。