例如,如果我需要在目录中获取文件,
封装形式:
struct dirent *ent;
ent = readdir (dir);
char *filename = d_name(ent);
C:
struct dirent *ent;
ent = readdir (dir);
char *filename = ent->d_name;
最佳答案
考虑以下两个API变体:
struct point get_location(const foo *f)
{
struct point p;
p.x = f->something_x;
p.y = f->something_y;
return p;
}
与:
double get_location_x(const foo *f)
{
return f->something_x;
}
double get_location_y(const foo *f)
{
return f->something_y;
}
我声称,关于后者,没有什么比前者更“封装”了。是否将前者的结果类型视为值类型只是一个角度问题。同样,
struct dirent
是一种值类型,其定义是明确规定的并且是稳定/固定的。正如@Jean-FrançoisFabre51所评论的那样,它是从封装在DIR
对象中的某些内部状态获得的结果值。关于c - 为什么某些C API不遵循封装,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48834047/