Sean
Sean

Reputation: 51

Friend function C++

Why doesn't this work?

I use friendly function in my code but there is an error so I can not find it. please help.

#include<iostream>
#include<cstdlib>
using namespace std;
class Circle{
private:
    int x;
public:
    Circle(int x1=5){
        x=x1;
        friend std:ostream & operator<<(const Circle & c, std::ostream & os)
        {
            return os<<c.x
        }
    }
};
int main()
{
    Circle s;
    cout<< s;
    system("pause");
    return 0;
}

Upvotes: 1

Views: 205

Answers (3)

godel9
godel9

Reputation: 7390

Four problems:

  1. You've defined the friend function inside the constructor. Move it outside so that it's its own function.

  2. Replace std:ostream with std::ostream

  3. Swap the order of the parameters.

  4. Add a semicolon after return os<<c.x

Final result:

class Circle{
private:
    int x;
public:
    Circle(int x1=5){
        x=x1;
    }
    friend std::ostream & operator<<(std::ostream & os, const Circle & c)
    {
        return os<<c.x;
    }
};

Upvotes: 3

Alan Stokes
Alan Stokes

Reputation: 18972

The friend function needs to be declared at the same level as the constructor, not inside it.

Upvotes: 1

rajenpandit
rajenpandit

Reputation: 1361

    friend std:ostream & operator<<(const Circle & c, std::ostream & os)
    {
        return os<<c.x
    }

you should declare this function outside the constructor.

Upvotes: 1

Related Questions