Friend functions should be able to access a class private members right? So what have I done wrong here? I've included my .h file with the operator<< I intent to befriend with the class.
#include <iostream>
using namespace std;
class fun
{
private:
int a;
int b;
int c;
public:
fun(int a, int b);
void my_swap();
int a_func();
void print();
friend ostream& operator<<(ostream& out, const fun& fun);
};
ostream& operator<<(ostream& out, fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
A friend class can access both private and protected members of the class in which it has been declared as friend.
Private: The class members declared as private can be accessed only by the member functions inside the class. They are not allowed to be accessed directly by any object or function outside the class. Only the member functions or the friend functions are allowed to access the private data members of the class.
A friend function in C++ is defined as a function that can access private, protected and public members of a class.
A friend function cannot access the private and protected data members of the class directly. It needs to make use of a class object and then access the members using the dot operator. A friend function can be a global function or a member of another class.
The signatures don't match. Your non-member function takes fun& fun, the friend declared on takes const fun& fun.
In here...
ostream& operator<<(ostream& out, fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
you need
ostream& operator<<(ostream& out, const fun& fun)
{
out << "a= " << fun.a << ", b= " << fun.b << std::endl;
return out;
}
(I've been bitten on the bum by this numerous times; the definition of your operator overload doesn't quite match the declaration, so it is thought to be a different function.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With