2021年4月3日星期六

how can I find the minimum distance between two point by using inheritance?

I would like to return a pointer to the object for which the distance is smallest by using getDistanceTo() method from Shape.cpp. But my findClosestTo() method will be core dumped. So how can I fix findClosestTo() method?

ShapeList.cpp

Shape* ShapeList::findClosestTo (double p_x, double p_y) const{      Shape* distance = nullptr;      for ( const auto& item : *this ) {          double longest  = item->getDistanceTo(p_x, p_y);          double previous = item->getDistanceTo(p_x, p_y);          longest = item->getDistanceTo(p_x, p_y);          if(previous > longest){              distance = item;          }      }      return distance;  }  

ShapeList.h

class ShapeList : protected std::list<Shape*> {  public:      ShapeList( ) = default;      ~ShapeList();      void add( Shape* newShape );      void write( std::ostream& strm_out ) const;      void erase();      Shape* findClosestTo (double p_x, double p_y) const;        friend std::ostream& operator<<( std::ostream& strm_out, const ShapeList& shapes );  };  

main.cpp

cout << "test \"closest\" methods...\n";  double x;  double y;  cout << "Enter coordinates for search of closest object reference: ";  cin  >> x >> y;  cout << "x: " << x << " y: " << y << endl;  Shape* closestObj = shapes2.findClosestTo( x, y );  cout << "closestObj: " << *closestObj << endl;  if ( closestObj != nullptr )      cout << "The object closest to the point provided is located at "           << *closestObj << endl;  

Shape.cpp

double Shape::getDistanceTo (double p_x, double p_y) const{      double distance;      distance = sqrt(p_x * ref_x + p_y * ref_y);      return distance;  }  
https://stackoverflow.com/questions/66935347/how-can-i-find-the-minimum-distance-between-two-point-by-using-inheritance April 04, 2021 at 03:56AM

没有评论:

发表评论