C++ 如何比较类中的两个对象(调用对象和参数)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2194762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:28:50  来源:igfitidea点击:

How to compare two objects (the calling object and the parameter) in a class?

c++oopclasscompare

提问by n-2r7

I am writing a "Date" class for an assignment and I am having trouble doing one the of the functions.

我正在为一项作业编写一个“日期”类,但在执行其中一个功能时遇到了麻烦。

This is the header file for the class.

这是类的头文件。

class Date
{
public:
Date();                                  // Constructor without parameters
Date(int m, int d, int y); // Constructor with parameters.

// accessors
int GetMonth();               // returns the size of the diamond
int GetDay();
int GetYear();

// mutators
bool Set(int m, int d, int y);
bool SetFormat(char f);

// standard input and output routines
void Input();             
void Show();              
void Increment(int numDays = 1);                 
int Compare(const Date& d);     

private:
int month,                    // month variables
    day,                 // day variable
    year;               // year variable
char format;
};

The member function I am trying to make is the int Compare(const Date& d) function. I need this function to compare two Date objects (the calling object and the parameter), and should return: -1 if the calling object comes first chronologically, 0 if the objects are the same date, and 1 if the parameter object comes first chronologically.

我正在尝试创建的成员函数是 int Compare(const Date& d) 函数。我需要这个函数来比较两个 Date 对象(调用对象和参数),并且应该返回:-1 如果调用对象按时间顺序首先出现,0 如果对象是相同的日期,如果参数对象按时间顺序首先出现则返回 1 .

I have tried doing a simple if statement with the == operator but I get errors.

我曾尝试使用 == 运算符做一个简单的 if 语句,但出现错误。

  if (d1 == d2)
     cout << "The dates are the same";
     return (0);

After the objects are created, the function should be called like this d1.Compare(d2)

创建对象后,应像这样调用该函数 d1.Compare(d2)

Thank you in advance!

先感谢您!

回答by Alexander Gessler

int Date :: Compare (const Date& d) {

   if (year<d.year) {
      return -1;
   }
   else if (year>d.year) {
      return 1;
   }
   else if (month<d.month) {
      return -1;
   }
   else if (month>d.month) {
      return 1;
   }
   // same for day

   return 0;
}

Usually, you'lll also want to provide overloaded comparison operators, for example (also within the class definition):

通常,您还需要提供重载的比较运算符,例如(也在类定义中):

bool operator == (const Date& d) const {
   return !Compare(d);
}

bool operator < (const Date& d) const {
  return Compare(d)<0;   
}

... // consider using boost::operators

PS: There are smarter implementations of Compare()- just check the other answers. This one is pretty straightforward and readable, but conforms exactly to your specification.

PS:有更智能的实现Compare()- 只需检查其他答案。这个非常简单易读,但完全符合您的规范。

回答by Steve Jessop

Here's how I might implement your Compare function, although the format takes a moment to get used to:

以下是我如何实现您的比较功能,尽管格式需要一些时间来适应:

int Date::Compare(const Date& d) const {
  return
    (year < d.year)   ? -1 :
    (year > d.year)   ?  1 :
    (month < d.month) ? -1 :
    (month > d.month) ?  1 :
    (day < d.day)     ? -1 :
    (day > d.day)     ?  1 :
                         0;
}

Or perhaps:

也许:

template<typename T>
int Compare(T a, T b) {
    if (a < b) return -1;
    if (b < a) return 1;
    return 0;
}

int Date::Compare(const Date& d) const {
    int a = Compare(year, d.year);
    if (a == 0) a = Compare(month, d.month);
    if (a == 0) a = Compare(day, d.day);
    return a;
}

I wouldn't use operator==in Compare, although the answers telling you how to implement operator==are fine if you want that as well. The reason is that operator==is clearly going to have to look at the same fields compare does, and if it returns false then Compare will do very similar work again. Efficiency probably isn't an issue, but it duplicates the logic.

我不会operator==在比较中使用,尽管告诉您如何实施的答案operator==也很好,如果您想要的话。原因是operator==显然必须查看 compare 相同的字段,如果它返回 false,Compare 将再次执行非常相似的工作。效率可能不是问题,但它重复了逻辑。

And for what it's worth, idiomatic C++ is to implement operator<and possibly also a consistent operator==and operator>, rather than an all-in-one Compare function. The operators are what the standard algorithms use for searching and sorting, and everything else follows. Java chose to do things differently.

就其价值而言,惯用的 C++ 将实现operator<并且可能也是一致的operator==and operator>,而不是多合一的比较函数。运算符是标准算法用于搜索和排序的东西,其他一切都在后面。Java 选择以不同的方式做事。

回答by Notinlist

into the class's publicarea

进入班级public区域

bool operator==(const Date& rhs) const {
    return
       year == rhs.year
       && month == rhs.month
       && day == rhs.day
    ;
}

回答by Eli Bendersky

Compare object by contents, i.e. in your case the dates are equal of the day, month and year are equal (and perhaps format- depending on your semantics).

按内容比较对象,即在您的情况下,日期等于日、月和年相等(也许format- 取决于您的语义)。

Also, C++ already includes a great facility for object comparison: operator ==which allows writing clearer code than calling a Comparemethod.

此外,C++ 已经包含了一个很好的对象比较工具:operator ==它允许编写比调用Compare方法更清晰的代码。

By the way, take care with this:

顺便说一句,请注意:

  if (d1 == d2)
     cout << "The dates are the same";
     return (0);

If the condition is true, the coutline will be executed. The returnwill be executed even if the condition is false.

如果条件为真,cout将执行该行。return即使条件为假,也将执行。

回答by Greg Bacon

The semantics of C++'s ||make this a little cluttered:

C++ 的语义||使这有点混乱:

static inline int cmp(int a, int b)
{
  return a < b ? -1 : a == b ? 0 : 1;
}

int Date::Compare(const Date& d)
{
  int result;
  (result = cmp(year, d.year))     ||
    (result = cmp(month, d.month)) ||
      (result = cmp(day, d.day));

  return result;
}

回答by John Dibling

In order to use operator== for user-defined types, you must implement it. In addition, your Compare function should be marked as a const member function:

为了将 operator== 用于用户定义的类型,您必须实现它。此外,您的 Compare 函数应标记为 const 成员函数:

class Date
{
...
int Compare(const Date& d) const;     

bool operator==(const Date& rhs) const
{
    return 0 == Compare(rhs);
}

回答by AlexPes

class Temp {

public:
       Temp(const char* str) {
         this->str = str;
         printf("Temp [%s] is created\n", this->str);
       }

       ~Temp() {
         printf("Temp [%s] is deleted\n", this->str);
       }

       bool operator == (const Temp& a) const {
         return this->str == a.str;
       }

private:
       const char* str = new char[10];
}

int main() {

   Temp test1{"Hello1"};
   Temp test2{"Hello2"};
   (test1 == test2) ? printf("Equals") : printf("Non equals");

   return 0;
}

回答by Vivin Paliath

You can't do d1 === d2, because I believe it compares the memory addresses (haven't done C++ in a while).

你不能做 d1 === d2,因为我相信它比较内存地址(有一段时间没有做 C++)。

What you need to do is write a function that will compare each member of your Date class and return negative number, 0, or positive number. Negative means lesser, 0 means the same, and positive means greater.

您需要做的是编写一个函数来比较 Date 类的每个成员并返回负数、0 或正数。负数表示较小,0 表示相同,正数表示较大。

For example, in Java:

例如,在 Java 中:

public int compareTo(Date date) {
  int returnValue = 0;

   returnValue = this.getYear() - date.getYear();

   if(returnValue == 0) {
      returnValue = this.getMonth() - date.getMonth();

      if(returnValue == 0) {
         returnValue = this.getDay() - date.getDay();
      }
   }
}