我必须compare(>,<,==)
两个 class 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
关于c++ - 使用 if else | 对象比较运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344242/