Archived

This topic is now archived and is closed to further replies.

daeron

operator <<

Recommended Posts

daeron    122
This code generates an error telling me I can''t access the private member variable and that the << call is ambigous. How can I make it work?

class CThing
{
public:
   friend ostream& operator<<(ostream& Os, const CThing& Out);

private:
   int data;
};

ostream& operator<<(ostream& Os, const CThing& Out)
{
   Os << Out.data;
   return Os;
}

CThing TheIt;
cout << TheIt; // <-- the operator doesn''t work

 
Have I missed something? - daeron

Share this post


Link to post
Share on other sites
Fruny    1658
beside the missing std namespace qualifier and constructor, it looks correct. I could compile & run with VC6 and g++.

Share this post


Link to post
Share on other sites
Dobbs    164
That's a semi-obscure bug in VC++ (I'm assuming you're using VC6 since that's a known problem with it). The best fix is to apply the latest Visual Studio service pack (5 I think).

Other workarounds if for some reason you don't want to patch VC6:
- don't include the whole std namespace, just the individual elements (cout) that you need
- declare the operator function before the class definition (I think you can just prototype it, but you might need to write out the implementation too)

Edited by - Dobbs on January 31, 2002 5:37:19 PM

Share this post


Link to post
Share on other sites
daeron    122
Btw, I tried not to include the whole std namespace and it worked. Will still download the service pack though, since it looks like an ugly work-around to me.

- daeron

Share this post


Link to post
Share on other sites