Y
Y
Yuri2021-11-29 17:10:19
C++ / C#
Yuri, 2021-11-29 17:10:19

How to override != and == operators in c++ for struct?

When iterating over a list of students, the compiler asks you to redefine the !=.
Here is the code snippet where I am trying to do it:

static student operator == (request c1, request c2)
  { 
    
    if (c1.Name == c2.Name)
      return;
      if(c1.MiddleName==c2.MiddleName)
      return;
    if(c1.Surname==c2.Surname)
      return;
        if(c1.language==c2.language)
      return;
    if(c1.languagelevel==c2.languagelevel)
      return;
    
  }
  static request operator != (request c1, request c2)
  {
     if (!(c1.Name == c2.Name))
       return ;
     if (!(c1.MiddleName == c2.MiddleName))
       return;

     if (!(c1.Surname == c2.Surname))
       return;

     if (!(c1.language == c2.language))
       return;

     if (!(c1.languagelevel == c2.languagelevel))
       return;
  }

Next, I'll show you what the fields look like:

wchar_t Name[80];
  wchar_t MiddleName[80];
  wchar_t Surname[80];
  wchar_t language[80];
  wchar_t languagelevel[80];
  Intensivity intensivity;

And this is how I iterate it:

for (list< request>::iterator it = requests->begin() ; it!=requests->back();it++ )

How to redefine operators so that iteration works correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-11-29
@uriy99

Operators must return bool and accept constant references to structures.
But in general, since you're iterating over a list, you're comparing iterators, not structs. Therefore, it is enough to simply use the standard construction:

for (auto it = requests->begin(); it != requests->end(); ++it)

And you don't need to redefine anything. You mixed up end and back. The first returns an iterator and the second returns an element.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question