operator overload problem
I make a "+" overload for my class as what CString does but found it cannot give the right result.
Here is my code:
CmyClass& operator +(CmyClass& a, CmyClass& b)
{
CmyClass c(...);
// assign a+b value to c
return c;
}
and then if i run
CmyClass a, b, c;
c = a+b;
give a wrong c result;
I have thought about c is supposed to have only local lifetime, but CString does the same
this is what CString does:
CString AFXAPI operator+(const CString& string1, const CString& string2)
{
CString s;
s.ConcatCopy(string1.GetData()->nDataLength, string1.m_pchData, string2.GetData()->nDataLength, string2.m_pchData);
return s;
}
Re: operator overload problem
You return local object by reference, what is wrong. CString returns local object by value (so it's returning a copy of local object), what is OK. You have to change return valuefrom CMyClass& to CMyClass.
Cheers,
Hob
Re: operator overload problem
And for const correctness, CmyClass should be passed as const reference.
Re: operator overload problem
Hobson,
Thank you for your help. Actually that is a typo. But i do have it solved by your words of "copy object". I forgot to make a copy construct function. Thank you!
Re: operator overload problem
Hi,
Once i add const prefix, i got an error below while compiling.
error C2662: 'Func' : cannot convert 'this' pointer from 'const class CMyClass' to 'class CMyClass &'
in Func, i return a class member;
do you know what the problem is? Thank you!
Quote:
Originally Posted by SuperKoko
And for const correctness, CmyClass should be passed as const reference.
Re: operator overload problem
I got it. i forget to use const member funcion in the class with const reference.
sorry to bother. I haven't used c++ for a while, some basics just slip out of my mind. :)
Quote:
Originally Posted by olin
Hi,
Once i add const prefix, i got an error below while compiling.
error C2662: 'Func' : cannot convert 'this' pointer from 'const class CMyClass' to 'class CMyClass &'
in Func, i return a class member;
do you know what the problem is? Thank you!
Re: operator overload problem