Перегрузка операторов сложения, вычитания +-

Производим перегрузку с помощью operator

В данном примере мы складываем и вычитаем оси X и Y, сравнивать можно любые поля класса в зависимости от смысла.

Перегрузка операторов
coordinate operator +(const coordinate& other) // перегрузка +
{
    coordinate temp;
    temp.x = this->x + other.x;
    temp.y = this->y + other.y;
    return temp;
}
coordinate operator -(const coordinate& other) // перегрузка -
{   
    coordinate temp;
    temp.x = this->x - other.x;
    temp.y = this->y - other.y;
    return temp;
}
coordinate A(2, 5);
coordinate B(5, 5);
coordinate C = A + B;

Last updated