Как использовать оператор перегрузки в качестве условия в статусе if? - PullRequest
0 голосов
/ 03 августа 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(){     
    this->x=x;
    this->y=y;
    this->radius=radius;
  }

  Circle(int x, int y, int radius){
this->x=x;
this->y=y;
this->radius=radius;
}
    void printCircleInfo() {
      cout << x << " " << y << " " << radius << " " ;
    }

Это оператор, который я хочу быть условием в моем операторе if.

bool operator==(const Circle &def){ 
  return (x==def.x) & (y==def.y) & (radius==def.radius);
}
    bool doIBumpIntoAnotherCircle(Circle anotherCircle){
      if (anotherCircle.radius + radius >=   *this - anotherCircle    )
    return true;
      return false;
    }

};

Вот main

int main(){
  int x,y,radius;
  const int SIZE = 13;
  Circle myCircleArry[SIZE];
  myCircleArry[0] = Circle(5,3,9);
   cout << endl;
   myCircleArry[0].printCircleInfo(); cout << " ; ";
  ifstream Lab6DataFileHandle;

  Lab6DataFileHandle.open("Lab6Data.txt");
  while (!Lab6DataFileHandle.eof( )) {
 for (int i = 1; i < SIZE; i++) {
Lab6DataFileHandle>>x;
Lab6DataFileHandle>>y;
Lab6DataFileHandle>>radius;
 myCircleArry[i] = Circle(x,y,radius);

 if (myCircleArry[0].doIBumpIntoAnotherCircle(myCircleArry[i])) {
      myCircleArry[i].printCircleInfo(); cout << " ; ";

Вот оператор If

      if ( operator==( Circle &def))
 {cout <<"*";
}


  }
  }
}
  Lab6DataFileHandle.close();

}

Как использовать перегруженный оператор в качестве условия оператора if? Если вам нужны какие-либо разъяснения, просто спросите иначе, оставьте пример в своем ответе. Спасибо за ваше время.

1 Ответ

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

A == требуется два аргумента (даже если перегрузка является членом), вы должны написать if как любой другой оператор if:

if(circle1 == circle2) { ... }

, и если есть соответствующая перегрузка, компилятор преобразует это во что-то вроде:

if(circle1.operator ==(circle2)) { ... }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...