结构体接口 [英] Structs interface

查看:29
本文介绍了结构体接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你定义一个新的struct时,最好也定义一个该类型的接口
(即setter"和getter"函数)或直接通过 .-> 运算符访问成员?

When you define a new struct is better to define also an interface to that type
(i.e. "setter" and "getter" functions) or to access members directly via . and -> operators?

编辑
纯C编程

推荐答案

这取决于你的结构体是否是抽象数据类型.如果您在标头中公开结构体定义,那么定义访问器就没有任何意义 - API 客户端仍然可以直接读取/写入字段,并且在 C 中,他们确实有合理的期望它会起作用.

It depends on whether your struct is an abstract data type or not. If you make the struct definition public in your header, then defining accessors doesn't make any sense - API clients can still read/write fields directly, and, in C, they do have reasonable expectation that it will work.

另一方面,您可能希望完全隐藏结构,只向客户端显示其声明,作为一种不透明的句柄:

On the other hand, you may want to hide the struct entirely, and only show its declaration to the clients, as a kind of an opaque handle:

foo.h:

typedef struct foo foo;

foo* foo_create();
void foo_free(foo*);
int foo_get_bar(foo*);
void foo_set_bar(foo*, int);

foo.cpp:

struct foo { 
  int bar;
};

foo* foo_create() { return malloc(sizeof(foo)); }

void foo_free(foo* p) { free(p); }

int foo_get_bar(foo* p) { return p->bar; }

void foo_set_bar(foo* p, int newval) { p->bar = nwval; }

client.cpp:

client.cpp:

#include "foo.h"

foo* f = foo_create();
f->bar = 123; // compile error, bar is not defined
foo_set_bar(f, 123); // ok

这样做的原因是 1) 封装,与 OO 中相同,以及 2) 版本控制 - 您可以向结构中添加新字段,或自由地重新组织它们,旧代码将保持二进制兼容.

The reason for doing it that way is 1) encapsulation, same as in OO, and 2) versioning - you may add new fields to your struct, or reorganize them freely, and old code will remain binary-compatible.

这篇关于结构体接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆