Sign in to follow this  
personwholives

Funb with private structures and friend functions

Recommended Posts

ok, heres the deal.....i have a class with a private struct in it i use for storing some data. i want to make a operator << for use with ostreams and my stuct. but i can't make it static, becuase the opertor isn't fonud for some reason, and i can't make it a friend because then i can't use the private struct in the function decleration. How do i fix this? thanks Heres some code:
class foo
{
private:
struct bleh
{
int r;
} bumpy;
public:
void DoStuff()
{
cout << bumpy;
}
static ostream& operator<<(ostream& out, bleh b);    //does not work, function is not found when cout << bumpy; is done above
friend ostream& operator<<(ostream& out, foo::bleh b);
};

//does not work, foo::bleh is private and cannot be accessed here
ostream& operator<<(ostream& out, foo::bleh b)
{
return out;
}
if this isn't technically possible, i guess it doesn't matter, but i would like to know if it can be done. Thanks personwholives

Share this post


Link to post
Share on other sites
#include <iostream>

class foo
{
private:
struct bleh
{
int r;
} bumpy;
public:
void DoStuff()
{
std::cout << bumpy;
}

friend std::ostream& operator<<(std::ostream& out, const foo::bleh& b);
};

std::ostream& operator<<(std::ostream& out, const foo::bleh& b)
{
return out << b.r;
}

int main()
{
foo f;
f.DoStuff();
}




Works without a hitch here on g++ 3.4.3, even with -Wall -pedantic -ansi.

Share this post


Link to post
Share on other sites
thanks, this appears to be a bug in vc6.....because the exact code used by Fruny does not compile.....and according to the only thing i found on google, this should be legal.....thanks you, microsoft.....

personwholives

Share this post


Link to post
Share on other sites
Your definition of the overloaded operator should come BEFORE you first use it, otherwise the compiler won't know what the heck you're trying to do.

Either move the definition before the call or declare the prototype in a header and then include that in a cpp file where you define "DoStuff" with the cout call. Then it'll know what you're doing.

[EDIT - grammar neeeded fixin']

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this