Question

I am making overloading ostream/istream operator function friend function of my class but it gives error : ostream does not name a type. without or with header file #include<iostream> it gives error

date.h:24:9: error: ‘ostream’ does not name a type friend ostream& operator<< (ostream &out, Date &today);
Was it helpful?

Solution

The name ostream is located in the std-namespace, so you need to introduce that name. The least intrusive way is to just qualify it explicitly:

friend std::ostream& operator<< ....
       ^^^

Another way is using a using- or using namespace-directive. They allow you to import the name/s to the rest of the translation unit:

using std::ostream; // cherry-pick the names
friend ostream& operator<< ....

or

using namespace std; // fire a shotgun with a huge and growing bunch of names
friend ostream& operator<< ....

These have advantages and disadvantages:

  • The name becomes shorter and might be better readable in the context
  • Name-Clashes may arise when other namespaces define the same names (consider e.g. std::pow vs. awesome_math_lib::pow).

An agreed upon rule-of-thumb for good C++-code is to never use using or using namespace in the global namespace in an header file, and with care in source files.

Many also agree that std:: is so short and standard, that they never use using or using namespace on it (except within functions) and just stick to typing std::....

OTHER TIPS

Change your declaration and implementation to use the fully qualified name for the type:

std::ostream& operator<<(std::ostream& os, Date& d)

Avoid using using namespace std; as it can (and likely will) cause naming conflicts - especially when used in header files (a big no-no).

You have to specify the namespace std using

std::ostream

in your code.

Another method is

using namespace std;

but it is not preferred.

You need to include header <iostream> and either use qualified name

std::ostream

or include directive

using std::ostream;

or even

using namespace std;

Standard class ostream for output streams is declared in name space std.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top