
question of operator overloading on function pointer
Quote:
> Hi All,
> I am trying my hand on operator overloading related to "cout<<endl;".
> I write my own class as following but can't get operator << invoked on
> my own endl. Could some anybody tell me what's wrong with my code.
> I did it on VC6.0 starting with an empty console project with option
> "Use MFC in a static libary"
> Thanks in advance!!
> Ray
> #include <afx.h>
> class COutObj
> {
> public:
> COutObj():m_strOut(""){};
> virtual ~COutObj(){};
> COutObj & operator <<(CString str){
> m_strOut+=str;
> return *this;
> };
> COutObj & operator <<(COutObj& ( * f1)(COutObj& outs)){
> (*f1)(*this); return *this;
> }
> COutObj& myendl(COutObj& outs){outs<<"myEndLine";return outs;}
> private:
> CString m_strOut;
> };
> void main(){
> COutObj mycout;
> mycout<<"aaaaaaaa"; file://ok
> mycout<<myendl; file://error C2065: 'myendl' : undeclared identifier
If you want this to compile you have to define myendl as a regular
function outside the class definition.
Quote:
> mycout<<COutObj::myendl;
> file://error C2678: binary '<<' : no operator defined
> file://which takes a left-hand operand of
> file://type 'class COutObj' (or there is no acceptable conversion)
You defined myendl as a non-static member function.
If you want this to compile you either have to define
it as a static member function
class COutObj
{
public:
// ...
static COutObj & myendl(COutObj& outs) { outs << "myEndLine"; return outs; }
// ...
Quote:
};
or define another operator << taking a pointer-to-member
class COutObj
{
public:
// ...
COutObj & operator << (COutObj & (COutObj::*pmf) (COutObj& outs)) {
(this->*pmf)(*this);
return *this;
}
// ...
Quote:
};
Sergei