Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ostream overloading be a function member?

Tags:

c++

I have a class Counter and I want to overload operator << to output the data member of Counter. I tried to make the ostream overloading a member function:

Counter{
public:
    std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
    int count_;
};

std::ostream& Counter::operator<<(std::ostream& outStream, const Counter& c){
    outStream << c.count_;
    return outStream;
}

But the g++ compiler always outputs the same error:

‘std::ostream& Counter::operator<<(std::ostream&, const Counter&)’ must take exactly one argument

However, if I changed the overloading function to be a friend of the class, it worked all well, like this:

Counter{
public:
    friend std::ostream& operator<<(std::ostream& outStream, const Counter& c);
private:
    int count_;
};

std::ostream& operator<<(std::ostream& outStream, const Counter& c){
    outStream << c.count_;
    return outStream;
}

Does this mean that the the stream operator overloading cannot be a member function of a class?

like image 723
Brian Avatar asked Sep 17 '25 18:09

Brian


1 Answers

Add a public query method that returns the value of count_, then it does not have to be a friend:

Counter{
public:
    int count() const { return count_; }
private:
    int count_;
};

std::ostream& operator<<(std::ostream& outStream, const Counter& c){
    outStream << c.count();
    return outStream;
}
like image 122
hmjd Avatar answered Sep 20 '25 07:09

hmjd