c++ - 使用 if else | 对象比较运算符重载

标签 c++ comparison operator-overloading

我必须compare(>,<,==)两个 class object基于不同的标准,解释如下。

class Student
{
    int iRollNumber;
    int iSection;
    int iMarks;
}
  1. 我想与 iRollNumber, iSection, iMarks 进行比较(独立)。
  2. 我想与 iRollNumber, iSection 进行比较(合并)。
  3. 我想与 iMarks, iSection 进行比较(合并)。
  4. ..........

目前我正在通过 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/

相关文章:

c++ - 在 Eclipse CDT 中的给定位置查看源代码中定义的所有宏

c++ - 确保具有 C++20 概念的类方法

c# - c# 中的(签名的)位图比较

typescript - typescript 中的数字比较

c++ - 数组大小和复制性能

c++ - 通用 lambda 在 C++14 中如何工作?

sql - 是否有表格比较 SQL 命令和 R 命令?

c++ - 使用引用而不是重载运算符

c++ - AVL 树中的比较由指向对象的指针组成

c# - 为什么在此运算符定义中抛出 stackoverflowexception?