I naturally included

#include <iostream>
using namespace std;

but the following overloading not works

friend ostream& operator<<(ostream& stream, mystruct& x);

just if I included std::

friend std::ostream& operator<<(std::ostream& stream, mystruct& x);

Why it is necessary?

Dani AI

Generated

Short answer: it was a name‑lookup/order problem. A friend declaration inside a class is parsed at the point where it appears, so if the using‑directive or using‑declaration that would make the stream type visible does not exist yet, the unqualified name is not found and the compiler forces an explicit std:: qualification (or a prior using‑declaration). That is what bit — the using directive was in the wrong place — and why ’s suggestion to bring the specific symbol into scope works.

The formal rules are in the language sections on friends and unqualified lookup; they explain why the scope and order of using‑directives matter. See cppreference - friend and cppreference - unqualified lookup for the normative behavior.

Practical guidance: avoid putting broad using‑directives in headers; prefer fully qualified names in declarations that are seen by other translation units. If the header only needs a declaration of the stream type, include <iosfwd> rather than heavy iostream headers, or add a targeted using‑declaration in the implementation file. Also define the output operator in the same namespace as your type so argument‑dependent lookup (ADL) works (see cppreference - ADL).

Quick checklist if this happens again: make sure the using directive/declaration is in effect before the class declaration, or fully qualify the stream type, or forward‑declare via iosfwd. This clarifies the scope/order issue without changing the intended operator semantics.

Recommended Answers

All 4 Replies

>> Why it is necessary?

Well, it shouldn't be... I tried the code separately on both GCC and minGW compilers, and both compiled well and didn't complain...

Try adding the statement

using std::ostream;

and try again...

using std::ostream; solves the problem
however I also use MinGW!?

I'm intrigued. Please post a complete (small!) program that exhibits the problem.

Sorry it was my fault, the using namespace was at wrong place

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.