Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

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

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:

Error: identifier "cout" is undefined

end

Error: identifier "endl" is undefined

Code:

#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;
};

Why it happens?

question from:https://stackoverflow.com/questions/13208547/the-includeiostream-exists-but-i-get-an-error-identifier-cout-is-undefine

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to specify the std:: namespace:

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

Alternatively, you can use a using directive:

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

cout << .... << endl;

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;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...