Reputation: 51
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
Reputation: 7390
Four problems:
You've defined the friend function inside the constructor. Move it outside so that it's its own function.
Replace std:ostream
with std::ostream
Swap the order of the parameters.
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
Reputation: 18972
The friend function needs to be declared at the same level as the constructor, not inside it.
Upvotes: 1
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