identifier "ostream" is undefined error [closed]
Asked Answered
A

2

12

i need to implement a number class that support operator << for output. i have an error: "identifier "ostream" is undefined" from some reason eventhough i included and try also

here the header file:

Number.h

#ifndef NUMBER_H
#define NUMBER_H
#include <iostream>
class Number{
public:
//an output method (for all type inheritance from number):
virtual void show()=0;

//an output operator:
friend ostream& operator << (ostream &os, const Number &f);


};

#endif

why the compiler isnt recognize ostream in the friend function?

Agglutinate answered 14/5, 2013 at 11:7 Comment(1)
Because as with all standard library types and functions, there just is no ostream. There's only std::ostream.Cuss
T
19

You need to fully qualify the name ostream with the name of the namespace that class lives in:

    std::ostream
//  ^^^^^

So your operator declaration should become:

friend std::ostream& operator << (std::ostream &os, const Number &f);
//     ^^^^^                      ^^^^^

Alternatively, you could have a using declaration before the unqualified name ostream appears:

using std::ostream;

This would allow you to write the ostream name without full qualification, as in your current version of the program.

Torn answered 14/5, 2013 at 11:8 Comment(3)
thanks alot! may using namespace std; will work either?Agglutinate
Although you shouldn't put using in the global namespace in a header, as that might cause name clashes for other users of the header.Crayon
@AviadChmelnik: It will work, but as Mike Seymour points out, it is considered a bad programming practice, because of the high likelihood of introducing name clashes (especially when put in a header at global namespace scope). Rather be selective if you canTorn
N
0

Andy Prowl's answer is great but please resist putting "using std::ostream" in a header. If you do this then other compilation units using your header file will also have this namespace 'used' by default and you can get nasty compilation errors with namespace clashes.

Nolpros answered 14/5, 2013 at 11:16 Comment(2)
using std::ostream puts one name into the namespace where it's used: ostream. That's nowhere near as big a problem as using namespace std;, which puts every name from std into that namespace.Tentative
Other compilation units will only get the ostream name, not the namespace. Still, I agree that it is a bad idea.Lebkuchen

© 2022 - 2024 — McMap. All rights reserved.