operator <<

Started by
3 comments, last by daeron 22 years, 2 months ago
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
- daeron
Advertisement
beside the missing std namespace qualifier and constructor, it looks correct. I could compile & run with VC6 and g++.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
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
Thanks, I''ll try and download the service pack.


- daeron
- daeron
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
- daeron

This topic is closed to new replies.

Advertisement