S
S
sabn1k2016-03-02 19:05:36
C++ / C#
sabn1k, 2016-03-02 19:05:36

Why do we need operator overloading in classes (STL)?

I started working with the STL theme and now when working with a user-defined data type, you always need to overload operations in the class, why? They are obviously not used anyway, how to understand when and why you need to overload the operation and which one?
For example, here the operators return bool, but where do they return it and what happens after that?

class airtime
{
private:
  int hours;
  int minutes;
public:
  airtime() : hours(0), minutes(0){}
  airtime(int h, int m) : hours(h), minutes(m){}
  void display() const
  {
    cout << hours << ':' << minutes;
  }
  void get()
  {
    char dummy;
    cout << "\nВведите время (формат 12:59): ";
    cin >> hours >> dummy >> minutes;
  }
  airtime operator+(const airtime right) const
  {
    int temph = hours + right.hours;
    int tempm = minutes + right.minutes;
    if (tempm >= 60)
    {
      temph++;
      tempm -= 60;
    }
    return airtime(temph, tempm);
  }
  bool operator==(const airtime& at2) const
  {
    return (hours == at2.hours) && (minutes == at2.minutes);
  }
  bool operator<(const airtime& at2) const
  {
    return (hours < at2.hours) || (hours == at2.hours && minutes < at2.minutes);
  }
  bool operator!=(const airtime& at2) const
  {
    return !(*this == at2);
  }
  bool operator>(const airtime& at2) const
  {
    return !(*this < at2) && !(*this == at2);
  }
};
int main()
{
  setlocale(LC_ALL, "Russian");
  char answ;
  airtime* temp = new airtime;
  airtime* sum = new airtime;
  list<airtime> airlist;
  do
  {
    (*temp).get();
    airlist.push_back(*temp);
    cout << "Продолжить (y/n)? ";
    cin >> answ;
  } while (answ != 'n');
  *sum = accumulate(airlist.begin(), airlist.end(), airtime(0, 0), plus <airtime>());
  cout << "\nСумма = ";
  (*sum).display();
  cout << endl;

  delete temp;
  delete sum;
  _getch();
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2016-03-02
@sabn1k

In my experience, operators are needed if you are using templates.
For example, stuff your objects into a std::vector and call std::sort(vec.begin(), vec.end());
In this case it will be used operator<to sort the values.
or for example write your own function

<template class T>
T sum3(T t1, T t2, T3) {
   return t1 + t2 + t3;
}

sum3(MyClass(), MyClass(), MyClass());
this code will only compile if you define MyClass::operator+.
The same std::sort can use operator() to compare objects, straight from the docs .
Well, in this spirit further.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question