Есть ли способ использовать оператор перегрузки как часть сравнения - PullRequest
1 голос
/ 02 августа 2020

Вот мой класс

#include <fstream>
#include <cstdlib>
#include <math.h>
#include <iomanip>
#include <iostream>
using namespace std;

class Point {
  protected:
    int x, y;

Вот оператор перегрузки, который я хочу использовать, он сравнивает разницу между двумя точками.

    double operator-(const Point &def){ 
        return sqrt(pow((x-def.x),2.0)+ 
                  pow((y-def.y),2.0));
    }

};

class Circle: public Point {
  private:
    int radius;

  public:
    Circle(){     //Point default const called implicitly
this->x=x;
this->y=y;
this->radius=radius;
}
    void printCircleInfo() {
      cout << x << " " << y << " " << radius << " " ;
    }
bool operator=(const Circle &def){ 
  return (x==def.x) & (y==def.y) & (radius==def.radius);
}
    bool doIBumpIntoAnotherCircle(Circle anotherCircle){

здесь я хочу использовать перегруженный оператор, чтобы сравнить расстояние между двумя точками с объединенным радиусом двух окружностей.

      if (anotherCircle.radius + radius >=   operator-( Point def)    )
    return true;
      return false;
    }

};

int main(){
  const int SIZE = 13;
  Circle myCircleArry[SIZE] = { 5,3,9};
;
  
  cout << myCircleArry[0] <<":";
  ifstream Lab6DataFileHandle;

  Lab6DataFileHandle.open("Lab6Data.txt");
  while (!Lab6DataFileHandle.eof( )) {
 for (int i = 1; i < SIZE; i++) {
Lab6DataFileHandle>>myCircleArry[i];
Lab6DataFileHandle>>myCircleArry[i];
Lab6DataFileHandle>>myCircleArry[i];
cout << endl;
 if (myCircleArry[0].doIBumpIntoAnotherCircle(myCircleArry[i])) {
      myCircleArry[i].printCircleInfo(); cout << " ; ";
      If double operator=(const Point &def)}
{cout <<"*"
}


  }
  }
  Lab6DataFileHandle.close();
}

}

Как использовать мой ранее созданный оператор перегрузки как часть моей функции bool doIBumpIntoAnotherCircle? Пожалуйста, оставьте пример в своем ответе, мы будем очень признательны. Спасибо за ваше время.

1 Ответ

0 голосов
/ 02 августа 2020

Да, вы можете напрямую использовать operator-, унаследованный от Point, например:

bool doIBumpIntoAnotherCircle(Circle anotherCircle){
    if (anotherCircle.radius + radius >= *this - anotherCircle)
        return true;
    return false;
}

Или проще:

bool doIBumpIntoAnotherCircle(Circle anotherCircle){
    return anotherCircle.radius + radius >=  *this - anotherCircle;
}

Кроме того, эта функция должна быть помечен как const и должен принимать параметр const&, например:

bool doIBumpIntoAnotherCircle(Circle const &anotherCircle) const {
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...