假设我们想要创建一个函数来计算两条线的交点。交点并不总是定义的或唯一的。如何在函数的签名中反射(reflect)这一点?
我想出了这些选项:
bool getIntersectionPoint ( Line& a, Line& b , Point& result );
如果直线平行则返回 false。否则返回 true 并将结果写入变量。
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/