c++ - 如何返回线交叉点?线并不总是相交

标签 c++ function exception return return-value

假设我们想要创建一个函数来计算两条线的交点。交点并不总是定义的或唯一的。如何在函数的签名中反射(reflect)这一点?

我想出了这些选项:

  1. bool getIntersectionPoint ( Line& a, Line& b , Point& result );

    如果直线平行则返回 false。否则返回 true 并将结果写入变量。

  2. Point getIntersectionPoint ( Line& a, Line& b );

    如果直线平行则抛出异常。

[更新]
如果我们制作 2 个函数 bool doLinesIntersect(const Line&, const Line&);Point twoLinesIntersection(const Line&, const Line&); 第二个仍然可以在第一个之后调用返回 false。

最佳答案

恕我直言,线相交产生对象,这就是为什么它是诚实的原因

boost::variant<Empty, Point, Line> intersect(Line const & l1, Line const & l2)

和辅助函数,比如

boost::optional<Point> getIntersectionPoint(Line const & l1, Line const & l2)

bool isParallel(Line const & l1, Line const & l2)

编辑: 如果您不想使用 boost 库,您可以轻松创建简单的类似物:

struct intersection_result_t
{
  enum isec_t
  {
    isec_empty, isec_point, isec_line
  }

  intersection_result_t()
    : type_(isec_empty)
  {
    new (storage_) Empty();
  }

  intersection_result_t(Empty const & e)
    : type_(isec_empty)
  {
    new (storage_) Empty(e);
  }
  intersection_result_t(Point const & p)
    : type_(isec_point)
  {
    new (storage_) Point(p);
  }
...
  intersection_result_t(intersection_result_t & ir)
    : type_(ir.type_)
  {
    switch(ir.type_)
    {
      case isec_empty:
        new (storage_) Empty(*static_cast<Empty*>(ir.storage_));
      case ....
    }
  }
private:
  void destroy()
  {
    switch(type_)
    {
      case isec_empty:
        operator delete (static_cast<Empty*>(storage_), storage_);
      case ....
    }
  }
private:
  char storage_[MAX(sizeof(Empty), sizeof(Point), sizeof(Line))];
  isec_t type_;
};

等等,等等,需要更多的开关。或者您可以使用模板。 对于可选的,只需使用 initialized_而不是 type_跟踪施工状态。

关于c++ - 如何返回线交叉点?线并不总是相交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15633761/

相关文章:

c++ - 如何为 linux 机器创建 Qt 可执行文件

delphi - 如何防止 Vista 因异常而终止我的程序?

c++ - 从 C++ "time.h"测量的运行时间是实际运行时间的两倍

c++ - 多重集 lower_bound 迭代器的位置

r - 使用 "FUN=first"跳过 NA 值

c# - 使用类或函数

javascript - 类似 JavaScript 中的 PreventDefault() 功能

python - 在循环中捕获异常回溯,然后在脚本末尾引发错误

PowerShell,异常处理 : Create custom logfile from Set-ADUser

c++ - 为什么 boost::diagnostic_information 崩溃了以及如何修复它?