简体   繁体   中英

Why does my compiler insist that operator<< has 3 parameters when it has 2?

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;
}

Layer is currently a dummy-class, getInputSize() and getSize() just return int s, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM