【问题标题】:Is there a way to use an overload operator as part of a comparison有没有办法使用重载运算符作为比较的一部分
【发布时间】:2020-08-02 17:25:33
【问题描述】:

这是我的课

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

}

如何将之前创建的重载运算符用作布尔函数 doIBumpIntoAnotherCircle 的一部分?请在您的回答中留下一个例子,我们将不胜感激。感谢您的宝贵时间。

【问题讨论】:

    标签: c++ class operator-overloading


    【解决方案1】:

    是的,你可以像这样直接使用继承自Pointoperator-

    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&amp; 的参数,如下所示:

    bool doIBumpIntoAnotherCircle(Circle const &anotherCircle) const {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      相关资源
      最近更新 更多