1
votes

I just started learning CPP and I'm having troubles with operator overloading. I want to overload the "<<" operator from the ostream lib. This is my declaration in the header file :

friend ostream& operator<<(ostream &out ,const Stone s);

and that is the cpp file:

ostream& Stone:: operator<<( ostream &out , const Stone s ){

The given error is : 1 IntelliSense: class "Stone" has no member "operator<<"

What am I doing wrong?

2
Don't post pictures of code, use copy-paste of the actual code instead. - Some programmer dude
You defined a member function, omit the Stone:: at the function definition. - πάντα ῥεῖ
As for your problem, declaring a friend function inside a class doesn't make the function a member function. - Some programmer dude

2 Answers

4
votes

The problem is your cpp file

std::ostream& Stone::operator<<(std::ostream& stream, const Stone s)
              ^^^^^
{
}

It's not a member function and should be:

// Also note the 2nd argument is `const &` (i.e., don't copy the object if you don't have to
std::ostream& operator<<(std::ostream& stream, const Stone& foo)
{

}

Full Example

If you're still having problems you should post more code and/or your errors. The following works for me.

#include <iostream>

class Foo
{
public:
    Foo() : mValue(99) {}

    friend std::ostream& operator<<(std::ostream& stream, const Foo& foo);

private:
    int mValue;
};

std::ostream& operator<<(std::ostream& stream, const Foo& foo)
{
    return stream << foo.mValue;
}

int main()
{
    Foo f;
    std::cout << f << "\n";

    return 0;
}
0
votes

In the header file, the friend declaration needs to be within the definition of class Stone.

In the source (you call it "cpp") file, the header file needs to be included before trying to define/implement the operator<<().

A friend is not a member, so should not be preceded by Stone::.

A couple of other niceties.

  • Never use using namespace std in a header file because it can cause ambiguity which is quite difficult to recover from. Name ostream in full (i.e. as std::ostream).

  • The second argument of operator<<() is usually best as a
    const reference, not passing by value.