views:

121

answers:

2
//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'm also trying to practice good coding. But my code wont compile unless i uncomment the using namespace std. i keep getting this error and i dont know. im using 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 somebody tell me the correct way to overload the << operator with out using namespace std;

+2  A: 

You have using std::ofstream instead of using std::ostream, so it doesn't know what ostream is.

You also need to include <ostream>.

Really, though, there's no reason to use using anything; you should just qualify the names with the namespace (especially if this is a header file, to avoid polluting the global namespace of other files):

friend std::ostream& operator<< (std::ostream&, const Dog&);
James McNellis
A: 

The using keyword just means to let you access something without prefixing it with its namespace. In orther words, using std::ofstream; just says to let you access std::ofstream as ofstream.

You also seem to need a #include <iostream>; that's why the compiler doesn't know what ostream is. Put that in, change the friend declaration to friend std::ostream& operator<< (std::ostream&, const Dog&);, and get rid of all the using stuff, since it's bad form to put using in a header, and you should be okay.

Mike DeSimone