【发布时间】:2017-06-14 18:21:24
【问题描述】:
我有以下功能:
/* Calculate if there is an intersection with given intial position and
direction */
vector<double> intersection(vector<double> startPos, vector<double> direction)
{
if(there is intersection)
return (intersection coordinates);
else {
return NULL;
}
}
我可以这样做并检查 NULL 是否存在交叉路口:
vector<double> v = intersection(pos, dir);
if(v == NULL)
/* Do something */
else
/* Do something else */
如果这是不允许/不好的编码习惯,我还有什么方法可以解决这个问题?
【问题讨论】:
-
向量不可能为NULL,但可以为空()。
-
也许看到这个问题:stackoverflow.com/q/29460651/10077
-
没有。 NULL 通常与指针一起使用。但是,您可以返回一个空向量并在另一边验证它是否为空。
-
您也可以返回一个指向向量的(共享)指针,但@NeilButterworth 的评论可能是首选。
-
您有 2 个选项:
1返回一个空向量。2抛出异常,因为函数无法履行其承诺。这取决于具体情况,哪个更合适。