#include<iostream>存在,但出现错误:标识符“cout"未定义.为什么? [英] The #include&lt;iostream&gt; exists, but I get an error: identifier &quot;cout&quot; is undefined. Why?

查看:341
本文介绍了#include<iostream>存在,但出现错误:标识符“cout"未定义.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

错误:标识符cout"未定义

Error: identifier "cout" is undefined

结束

错误:标识符endl"未定义

Error: identifier "endl" is undefined

代码:

#include<iostream>
#include"interfaces.h" // unknown.h, objbase.h, initguid.h

class CA {//: public IX, IY{
public:
    // Constructor
    CA();
    // Destructor
    ~CA();
    // IUnknown
    virtual HRESULT __stdcall QueryInterface(const IID& iid, void** ppv);
    virtual ULONG __stdcall AddRef();
    virtual ULONG __stdcall Release();
    // IX
    virtual void __stdcall Fx1();
    virtual void __stdcall Fx2();
    // IY
    virtual void __stdcall Fy1(){ cout << "Fy1" << endl; }  // errors here
    virtual void __stdcall Fy2(){ cout << "Fy2" << endl; }  // errors here also
private:
    long counter;
};

为什么会这样?

推荐答案

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

You need to specify the std:: namespace:

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

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

Alternatively, you can use a using directive:

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

cout << .... << endl;

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

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

#include <iostream>

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

此处,using 指令仅适用于 foo() 的作用域.

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

这篇关于#include<iostream>存在,但出现错误:标识符“cout"未定义.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆