c++方法返回指针:分段错误



下面的代码给了我一个分割错误,我已经尝试了很多不同的东西,但不能得到为什么它不会工作的hang。我对c++很陌生,所以我很抱歉,如果这个问题可能有点容易;)下面是我的代码:

 class Line2D
 {
 public:
   Point2D punkt; 
   double dx, dy; 
   void set_values(Point2D p, double d1, double d2);
   Point2D* getIntersectionPoint(Line2D& line2);
 };
 void Line2D::set_values(Point2D p, double d1, double d2)
 {
   punkt = p;
   dx = d1;
   dy = d2;
 }
 Point2D* Line2D::getIntersectionPoint(Line2D& line2)
 {
   double a, b;
   Point2D* intersec; 
   double det = dx*line2.dy - dy*line2.dx;
   if(det == 0)
   {
     return NULL;
   }
   else
   {
     double c1 = line2.punkt.k1 - punkt.k1;
     double c2 = line2.punkt.k2 - punkt.k2;
     a = (line2.dy*c1 - line2.dx*c2)/det;
     b = (dx*c2 - dy*c2)/det;
   }
   intersec->set_values(a,b);
   return intersec;
 }

 int main()
 {
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   Point2D* intersec;
   intersec = l1.getIntersectionPoint(l2);
 }

你有

Point2D* intersec; 

,未初始化为指向任何有效对象。

为它分配内存并使用它之后的指针

Point2D* Line2D::getIntersectionPoint(Line2D& line2)
{
   double a, b;
   // Initialize the pointer to NULL so
   // that it will be easy to detect when it
   // points to valid object.
   Point2D* intersec = NULL;
   double det = dx*line2.dy - dy*line2.dx;
   if(det == 0)
   {
     return NULL;
   }
   else
   {
     double c1 = line2.punkt.k1 - punkt.k1;
     double c2 = line2.punkt.k2 - punkt.k2;
     a = (line2.dy*c1 - line2.dx*c2)/det;
     b = (dx*c2 - dy*c2)/det;
   }
   // Allocate memory for a Point2D
   intersec = new Point2D;
   intersec->set_values(a,b);
   return intersec;
}

确保删除main中的返回对象。

int main()
{
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   Point2D* intersec;
   intersec = l1.getIntersectionPoint(l2);
   // Use intersec
   // ...
   // ...
   // Delete intersec before the end of main.
   delete intersec;
}

可以在main完成后使用std::shared_ptr自动删除对象。

int main()
{
   //...
   Line2D l1;
   Line2D l2;
   l1.set_values(p3,6,3);
   Point2D p11;
   p11.set_values(1,6);
   l2.set_values(p11,4,0);
   std::shared_ptr<Point2D> intersec = l1.getIntersectionPoint(l2);
   // Use intersec
   // ...
   // ...
}

相关内容

  • 没有找到相关文章

最新更新