【发布时间】:2019-12-31 17:51:56
【问题描述】:
假设我有以下结构:
struct cube {
int height;
int length;
int width;
};
我需要创建一个库,允许用户将值输入到结构中,然后将其传递给函数,该函数将确定用户是否需要提供的值中的 area 或 volume。
例如:
int main() {
struct cube shape;
shape.height = 2;
shape.width = 3;
printf("Area: %d", calculate(shape)); // Prints 6
shape.length = 4;
printf("Volume: %d", calculate(shape)); // Prints 24
return 0;
}
int calculate(struct cube nums) {
if (is_present(nums.height, nums) && is_present(nums.width, nums)) {
return nums.height * nums.width;
}
else if (is_present(nums.height, nums) && is_present(nums.width, nums) && is_present(nums.length, nums)) {
return nums.height * nums.width * nums.length;
}
else {
return -1; // Error
}
}
如果我可以使用一个函数(例如我刚刚编造的is_present())来确定一个值是否被赋予了一个结构的成员,这应该可以工作。
有没有这样的功能,如果没有,怎么实现?
【问题讨论】:
-
没有,你必须做一些事情,比如给高度/长度/宽度-1,然后测试它(代替你的 is_present 函数)。或者你可以做一个不透明的结构并有一个 get/set 函数。这样你就知道了。
-
为什么允许
cube的无效实例存在?为什么不通过在创建它之前检查缺失的字段来避免这个问题?
标签: c function struct variable-assignment standard-library