0

This seems so simple, and I've overloaded operators before, but now i get the error message error: overloaded 'operator<<' must be a binary operator (has 3 parameters). I feel like there is something obvious I'm missing, but after googling for some hours I just can't seem to figure it out ... In my .h file i have this

class NeuralNet{
    private:
        vector<Layer*> layers;
    public:
        NeuralNet(){}
        void addLayer(Layer*);
        friend ostream& operator<<(ostream&, const NeuralNet);
};

and in my .cpp file I have this

ostream& NeuralNet::operator<<(ostream& os, NeuralNet& net){
    for (Layer* l : net.layers){
        os << l->getSize() << " ";
    }
    os << "\n";
    for (Layer* l : net.layers){
        os << l->getInputSize() << " ";
    }
    os << endl; 
    return os;
}

Layeris currently a dummy-class, getInputSize() and getSize() just return ints, there are no self-defined namespaces involved. I want to keep the vector<Layer*> layers private, and I have written code earlier using friend so that operator<< can be allowed to access private variables. However now, if i don't declare operator<< as friend and remove the NeuralNet:: in the .cpp file I (obviously) get the error error: 'layers' is a private member of 'NeuralNet', but when I include it i get said error message.

  • 1
    This might not be a satisfactory explanation but you have `const NeuralNet` in your declaration's signature and `NeuralNet&` in your definition. Both should be `const NeuralNet&`. Does that change the error message? – alter_igel May 22 '20 at 21:06
  • 1
    Friend functions aren't members of a class. Remove the `NeuralNet::` from your definition. – eesiraed May 22 '20 at 21:07
  • 3
    `NeuralNet::operator<<(...)` is the definition of a member function. Has an implicit `this` argument like all non-static member functions. – Mat May 22 '20 at 21:07
  • @Vegard Jervell It is just a silly compiler. It shall say that such a member function does not exist.:) – Vlad from Moscow May 22 '20 at 21:17
  • Thanks all! I believe it was a combination of the above that made me introduce new errors when fixing other ones :P Silly mistakes that, show up around 23:30... thanks again for friendly help :) – Vegard Gjeldvik Jervell May 23 '20 at 06:57

1 Answers1

2
ostream& NeuralNet::operator<<(ostream& os, NeuralNet& net){ ... }

needs to be

ostream& operator<<(ostream& os, NeuralNet& net){

since you have declared it to be friend function, not a member function.

R Sahu
  • 204,454
  • 14
  • 159
  • 270