Overload = operator on custom class
| gmorgs3 (9) | |||||
| Hi all, I've looked through £100's worth of text books and all the code I can find but I jsut can't work out how to be able to make a comparison between two class variables, i.e. if ( a_class A = a_class B ) { return 1; } I'm trying to apply this concept to compare dates in a custom date of birth class: Here's the header file:
And here's the function file:
It seems like such a simple concept in my head but I cant get the code to reflect that! Sorry for the trouble, any help would be greatly appreciated! Thank you very much, Gareth. | |||||
| Duoas (1378) | |||
| The assignment operator is a tad unusual as far as operator overloading goes. It generally takes the form:
There are other caveats. 1. Watch out for self assignment. http://www.parashift.com/c++-faq-lite/assignment-operators.html 2. If you overload the assignment operator, you should almost always overload the copy constructor also (and vice-versa). 3. Beware the nasties: http://www.icu-project.org/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html Good luck. | |||
| gmorgs3 (9) | |||
| Thanks for your reply! Okay... I've spent ages messing about with this but I jsut can't get it to work, there must be 20 errors or so when I run my = operator. I've read both those sites but their examples are quite different from mine and I'm unable to translate them to my code. Im at this stage so far:
But it doesn't like that at all! EDIT: Just thought... I'm trying to COMPARE two dates, not make one equal to the other, so whe I need to overload is the '==' operator. Doh! Back to the drawing board. Double Edit: void dob::dob operator==(dob &x) {} ??? | |||
| jsmith (379) | |||
| Do you want assignment (operator=) or comparison (operator==)? In your above code, you just need to remove the asterisks from *x. However, you should also make your x parameter a const reference and you also have an extraneous "dob":
dob& dob::operator=( dob const& x ) { ... }If you want comparison, operator== is very similar in syntax:
| |||
| gmorgs3 (9) | |||
| Its a comparison operator I need. I tried this: Base class
dob operator==( const dob &rhs ); // operates on x Function file
but it comes up with all sorts of errors. Hmm. | |||
| Duoas (1378) | |||||
That's because your syntax stinks... watch your syntax:
Hope this helps. | |||||
| gmorgs3 (9) | |||
| It sure does! Tried and tested. Thank you so much! | |||
This topic is archived - New replies not allowed.
