Overloading the I/O operator problem

Started by
6 comments, last by stodge 21 years, 2 months ago
I''m trying to overload the << operator using:
  inline ostream &operator<<(ostream &o, const HBchar* ch)
{
	return o;
}  
I copied this straight from my C++ book. Visual Studio is telling me that:
quote:error C2804: binary ''operator <<'' has too many parameters
Am I going mad or doing something really stupid? Thanks
---------------------http://www.stodge.net
Advertisement
Looks right to me :\

In fact, this code compiled and ran perfectly for me (VS.NET)

  #include <iostream>using namespace std;struct HBchar{};inline ostream& operator<<(ostream& o,const HBchar* c){		return o;}int main(){	HBchar* hb = new HBchar[10];	cout << hb << endl;	delete [] hb;	return 0;}  
daerid@gmail.com
Weird: it just won''t compile for me.
---------------------http://www.stodge.net
Did you place it inside a class?

Remember, class member functions (methods) have an extra, implicit parameter (the this pointer); ostream operators must be defined inside the ostream class (which you can''t do) or as global functions.
Oh:


  	class HBCOREENGINE_API hbLogManager :			public hbBaseManager,			public hbBaseEventObserver	{	public:		hbLogManager();		virtual ~hbLogManager();		HBboolean Initialise();		HBboolean Shutdown();		void ActionEvent(hbBaseEvent *event);		static hbLogManager* GetInstance();		void LogMsg(HBstring msg);						std::ostream &operator<<(std::ostream &o, const HBchar* ch);					private:		static hbLogManager*	mInstance;		hbLogMsgEvent			mLogMsgEvent;	};    


[edited by - stodge on January 30, 2003 9:34:55 PM]
---------------------http://www.stodge.net
if its inside a class try a friend function


edit: i guess that might not be what you are trying to do though... sorry

[edited by - fartocci on January 30, 2003 9:39:12 PM]
it needs to be outside of the class

if it needs to access the internals, either make the function a friend (which I''d usually advise against, but this is so common and only one function that you''re giving access) or rather have an output function which does all the work.

note that I''m passing by reference rather than pointer as it makes the calling more consistent with how it is normally used. Also passing the correct object type (don''t know what HBchar is.

  inline ostream &operator<<(ostream &o, const hbLogManager& ch){    return ch.output(o)}  
Technically you could make that operator a member of the class, but like Miserable said, there is an assumed parameter. For overloaded binary operators, the class type is assumed to be the L-value.

So now the class is the L-value and the stream is the R-value. You can then use it in a very funky way:

MyClass << cout;

I think that sort of statement defeats the purpose of overloading operators in the first place however (what exactly does it mean when you insert a stream into your class?)

This topic is closed to new replies.

Advertisement