c++ - 有没有一种方法可以使用重载运算符作为比较的一部分

标签 c++ class operator-overloading

Here is my class

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

class Point {
  protected:
    int x, y;

Here is the overload operater I want to use it compares the difrence between two points.

    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){

here I want to use the overloaded operater to compare the distance between the two points to the combined radius of two circles.

      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();
}

}

How do I use my previously created overload operator as part of my bool function doIBumpIntoAnotherCircle? Please leave an example in your answer it would be much appreciated. Thank you for your time.

最佳答案

是的,您可以像这样直接使用从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 {

关于c++ - 有没有一种方法可以使用重载运算符作为比较的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63219060/

相关文章:

c++ - 打印奇怪的结果

c++ - 什么是 std::strtoul for unicode

java - 声明引用时是否加载类?

java - 使用不同名称声明多个对象

c++ - 如何为 lambda 赋值重载 operator=?

c++ - 在 Vector Container 中使用 placement new

c++ - QT 文本编辑小部件中的引号

java - 在 Java 中使用同名包中的类

matlab - 为什么 Matlab R2010 不能从 R2007 加载神经网络对象?

c++ - operator<< 重载调用打印函数麻烦