Operator << overload
//using namespace std; using std::ifstream; using std::ofstream; using std::cout; class Dog { friend ostream& operator<< (ostream&, const Dog&); public: char* name; char* breed; char* gender; Dog(); ~Dog(); };
im trying to overload the <operator. I am also trying to practice good coding. But my code won't compile unless I uncomment the use of the std namespace. I keep getting this error and I don't know. im using the g ++ compiler.
Dog.h:20: error: ISO C++ forbids declaration of โostreamโ with no type Dog.h:20: error: โostreamโ is neither function nor member function; cannot be declared friend. if i add line using std::cout; then i get this error. Dog.h:21: error: ISO C++ forbids declaration of โostreamโ with no type.
Can someone tell me the correct way to overload the <operator without using the std namespace;
source share
You have using std::ofstream
instead using std::ostream
, so he doesn't know what it is ostream
.
You also need to enable <ostream>
.
Indeed, there is no reason to use using anything
; you should just qualify names with a namespace (especially if it's a header file so as not to pollute the global namespace of other files):
friend std::ostream& operator<< (std::ostream&, const Dog&);
source share
The keyword using
means you can access anything not prefixed with its namespace. In words, orter, using std::ofstream;
just says so you can access std::ofstream
how ofstream
.
You also seem to need #include <iostream>
; why the compiler doesn't know what is ostream
. Put this in, change your friend's ad to friend std::ostream& operator<< (std::ostream&, const Dog&);
and get rid of all the stuff using
, as this is a bad form to post using
in the headline and you should be fine.
source share