在 C 结构中隐藏成员 [英] Hiding members in a C struct

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

问题描述

我一直在阅读 C 语言中的 OOP,但我从不喜欢你不能像在 C++ 中那样拥有私有数据成员.但后来我想到你可以创建 2 个结构.一个在头文件中定义,另一个在源文件中定义.

I've been reading about OOP in C but I never liked how you can't have private data members like you can in C++. But then it came to my mind that you could create 2 structures. One is defined in the header file and the other is defined in the source file.

// =========================================
// in somestruct.h
typedef struct {
  int _public_member;
} SomeStruct;

// =========================================
// in somestruct.c

#include "somestruct.h"

typedef struct {
  int _public_member;
  int _private_member;
} SomeStructSource;

SomeStruct *SomeStruct_Create()
{
  SomeStructSource *p = (SomeStructSource *)malloc(sizeof(SomeStructSource));
  p->_private_member = 42;
  return (SomeStruct *)p;
}

从这里您可以将一个结构投射到另一个结构上.这被认为是不好的做法吗?还是经常做?

From here you can just cast one structure to the other. Is this considered bad practice? Or is it done often?

推荐答案

就我个人而言,我更喜欢这样:

Personally, I'd more like this:

typedef struct {
  int _public_member;
  /*I know you wont listen, but don't ever touch this member.*/
  int _private_member;
} SomeStructSource;

毕竟是 C,如果人们想搞砸,他们应该被允许 - 不需要隐藏东西,除了:

It's C after all, if people want to screw up, they should be allowed to - no need to hide stuff, except:

如果您需要保持 ABI/API 兼容,有两种方法比我所见更常见.

If what you need is to keep the ABI/API compatible, there's 2 approaches that's more common from what I've seen.

  • 不要让你的客户访问结构体,给他们一个不透明的句柄(一个有漂亮名字的 void*),为所有东西提供 init/destroy 和 accessor 函数.这确保你可以改变如果您正在编写一个库,甚至不需要重新编译客户端的结构.

  • Don't give your clients access to the struct, give them an opaque handle (a void* with a pretty name), provide init/destroy and accessor functions for everything. This makes sure you can change the structure without even recompiling the clients if you're writing a library.

提供一个不透明句柄作为结构的一部分,您可以随意分配.这种方法甚至用于 C++ 以提供 ABI 兼容性.

provide an opaque handle as part of your struct, which you can allocate however you like. This approach is even used in C++ to provide ABI compatibility.

例如

 struct SomeStruct {
  int member;
  void* internals; //allocate this to your private struct
 };

这篇关于在 C 结构中隐藏成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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