开发者

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;
}
  1. I want to do comparison with iRollNumber, iSection, iMarks (Independently).
  2. I want to do comparison with iRollNumber, iSection (Combined).
  3. I want to do comparison with iMarks, iSection (Combined).
  4. ..........

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜