#include <iostream>
usingnamespace std;
class A
{
private:
int x;
public:
A(int a = 1) {x = a;}
friend ostream& operator<<(ostream & o, A instance)
{
return (o << instance.x);
}
};
I think I understand what's going on here... we're overloading the ostream::operator<<() function to work with our A class, and thus it needs to be a friend function so we can "access" that method and overload it? Is that right? Is there a better way to phrase it?
Thanks.
EDIT:
Also, is there a way to implement the function outside of the header?.. or is it necessary for it to be there?
It is a friend function so that the function can access the private members within A. It has nothing to do with the fact that the function is outside it.
You can, just like any other function (almost):
1 2 3 4 5 6
class A
{
//...
friend ostream& operator<< (ostream& str, const A& inst);
//...
}
[/code]
ostream& operator<< (ostream& str, const A& inst) { //no friend here
str << inst.x; //since it is a friend function, we can access x directly without get/set functions
return str;
}
[/code]
So long as your programs are in the same project, you can take a separate CPP file and define all your functions in that file, while including your header in that file. Including the header should also work fine so long as it's in a place where the compiler can find it. (In the same folder as the project, or in the Header folder for your compiler)
NGen, I knew about #include ing header files and such but I was wondering if I was supposed to do something like friend ostream& A::operator<<( but that didn't make any sense because I figured it was the ostream's operator<< so I didn't really understand how to implement it in the .cpp file.
but firedraco cleared things up. I get it now, thank you.