问题描述
|
我必须根据不同的标准将
compare(>,<,==)
2class object
,如下所述。
class Student
{
int iRollNumber;
int iSection;
int iMarks;
}
我想和iRollNumber,iSection,iMarks
做比较(独立地)。
我想和iRollNumber,iSection
(组合)做比较。
我想和iMarks,iSection
(组合)做比较。
..........
目前,我正在使用GetMethods()
实现此目标,并使用if elseif elseif..
结构对其进行比较。
这导致到处都是凌乱的代码!
如果我使用operator overloading
,则必须决定一种比较方式。
请提出一种使用优雅编码的方法。
要么
可以调用操作符多态重载吗?
解决方法
编写命名函数:
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 );
尽管在一个类上需要进行许多不同种类的比较有点不寻常-通常您只需要一个或两个即可。函数应返回与strcmp()相同类型的值:
< returns -1
== returns 0
> returns 1