Object Comparison using if else | Operator Overloading
I have to compare(>,<,==)
two class object
based upon different criteria, explained below.
class Student
{
int iRollNumber;
int iSection;
int iMarks;
}
- I want to do comparison with
iRollNumber, iSection, iMarks
(Independently). - I want to do comparison with
iRollNumber, iSection
(Combined). - I want to do comparison with
iMarks, iSection
(Combined). - ..........
Currently I am achieving this with GetMethods()
and comp开发者_如何学编程aring them using if elseif elseif..
structure.
This is leading to the messy code everywhere!
If I use operator overloading
I have to decide on one way of comparison.
Please suggest a way to do it with elegant coding.
Or
Can it be possible to call operator overloading Polymorphically?
Write named functions:
int CompareR( const Student & a, const Student & b );
int CompareS( const Student & a, const Student & b );
int CompareM( const Student & a, const Student & b );
int CompareRS( const Student & a, const Student & b );
int CompareMS( const Student & a, const Student & b );
although the need to do so many different kinds of comparison on a class is a bit unusual - you normally only need one or perhaps two. The functions should return the same kind of values as strcmp() does:
< returns -1
== returns 0
> returns 1
精彩评论