class has no member "operator<<"
Asked Answered
V

1

5

I have read through Should operator<< be implemented as a friend or as a member function? and Overloading Insertion Operator in C++, looks like the similar problem, but didn't fix my own problem.

My header file:

using namespace std;

class Animal {
private: 
    friend ostream & operator<< (ostream & o, Dog & d);
    int number;
public:
    Animal(int i);
    int getnumber();

};

ostream & operator<< (ostream & o, Dog & d);

My cpp:

using namespace std;

int Animal::getnumber(){
    return number;
}

ostream & Animal::operator<< (ostream & o, Dog & d){
    //...
}

Animal::Animal(int i) : number(i){}

Implementation is simple, but I am getting the error: in cpp - Error: class "Animal" class has no member "operator<<". I don't really get it because I already declared insertion operator as a friend in Animal, why am I still getting this error? (put the ostream in public doesn't help)

Verile answered 11/3, 2013 at 2:46 Comment(0)
B
8

It's not a member of the Animal class, nor should it be. So don't define it as one. Define it as a free function by removing the Animal:: prefix.

ostream & operator<< (ostream & o, Dog & d){
    //...
}
Bathy answered 11/3, 2013 at 2:48 Comment(1)
If you don't want to make operator<< a friend function, have it delegate to a (possibly virtual) member function: ostream& operator<<(ostream& o, Dog& d) { d.print_to_stream(o); }Rehearse

© 2022 - 2024 — McMap. All rights reserved.