具有许多参数的函数——将它们作为结构体
Functions with many parameters - making them as structs
我正在为内部需求编写API,因此易用性是最优先考虑的问题之一。我想知道我是否像下面的例子那样做得太过火了。
求解逆大地测量问题的函数取两点的地理坐标,计算两点之间的距离和两点之间的近似角(角度)。
易用性优化的传统解决方案可能看起来像这样(请不要介意名称的长度,我知道还有改进的空间):
class Angle;
class GeoCoordinate;
...
struct InverseGeodeticOut
{
Angle forwardAzimuth;
Angle backAzimuth;
double distance;
};
InverseGeodeticOut inverseGeodetic(const GeoCoordinate &firstPoint,
const GeoCoordinate &secondPoint);
// or
void inverseGeodetic(const GeoCoordinate &firstPoint,
const GeoCoordinate &secondPoint,
InverseGeodeticOut *result);
我的问题是,如果再进一步为用户节省一些输入,这是否合理:
class Angle;
class GeoCoordinate;
...
struct InverseGeodetic
{
InverseGeodetic();
InverseGeodetic(const GeoCoordinate &firstPoint,
const GeoCoordinate &secondPoint);
Angle forwardAzimuth;
Angle backAzimuth;
double distance;
};
// so the usages would be
InverseGeodeticOut inverse = inverseGeodetic(firstPoint, secondPoint);
InverseGeodeticOut inverse;
inverseGeodetic(firstPoint, secondPoint, &inverse);
InverseGeodetic inverse(firstPoint, secondPoint);
也许在这个特殊的例子中,差异太小,不值得讨论,但我想知道这样的结构是否在一般情况下是可以的。
我喜欢你的第二个代码示例,尽管我发现公共构造函数有点令人困惑。特别是如果有其他方法来构造InverseGeodetic
。我宁愿使用静态工厂方法来构造它。这样你就可以给方法起一个更有意义的名字:
struct InverseGeodetic
{
Angle forwardAzimuth;
Angle backAzimuth;
double distance;
static InverseGeodetic FromTwoPoints(const GeoCoordinate &, const GeoCoordinate &);
};
// usage
auto inverse = InverseGeodetic::FromTwoPoints(a, b);
但这可能是我的c#背景。
相关文章:
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- C++ - 如何在结构向量中找到结构体一个成员的最大值?
- 包含 std::list 的结构体的 C++ 初始化
- 结构体和类的不同大小(),彼此具有相同的字段类型
- 如何使用结构体的向量数组?
- 如何使用结构体在C++中更改这些代码?
- 无法在 Mosquitto MQTT Broker 插件上访问结构体 mosquitto 的元素
- 我应该如何在C++中使用结构体解决输入失败的问题?
- Qsort() 比较结构体整数的总和
- 如何使用迭代器指向结构体c++的向量
- 在C++中使用链表的堆栈实现中,访问结构体headNode成员count和top会导致运行时错误
- 如何获取结构体成员的地址
- 创建结构体向量,表达式:向量下标超出范围
- boost::任何带有结构体和无符号整数
- 如何在构造函数中初始化结构体的动态数组?
- 只写结构体的某些字段
- C++ push_back() 一个结构体到一个向量中
- 具有许多参数的函数——将它们作为结构体
- 一个结构体的深度拷贝,它嵌入了许多简单的变量和一个嵌套结构体