gpt4 book ai didi

c - C 中的数据抽象

转载 作者:太空狗 更新时间:2023-10-29 15:00:44 26 4
gpt4 key购买 nike

我对数据抽象的理解是向用户隐藏技术细节并仅显示必要的细节。所以数据抽象是一个 OOP 特性。我的问题是:C 是否也支持数据抽象?

如果是这样,为什么数据抽象是一种面向对象的编程语言特性而不是过程语言特性?

如果我的问题的答案是,那么 C 中的结构、枚举呢?他们还向用户隐藏详细信息。

最佳答案

在 C 中进行面向对象编程当然是可能的。请记住,例如first C++ compiler实际上是 C++ 到 C 的转译器,Python VM 是用 C 等编写的。所谓的 OOP 语言与其他语言的区别在于对这些结构的更好支持,例如语法。

提供抽象的一种常见方法是函数指针。查看下面 Linux 内核源代码中的结构(来自 include/linux/virtio.h)。

/**
* virtio_driver - operations for a virtio I/O driver
* @driver: underlying device driver (populate name and owner).
* @id_table: the ids serviced by this driver.
* @feature_table: an array of feature numbers supported by this driver.
* @feature_table_size: number of entries in the feature table array.
* @probe: the function to call when a device is found. Returns 0 or -errno.
* @remove: the function to call when a device is removed.
* @config_changed: optional function to call when the device configuration
* changes; may be called in interrupt context.
*/
struct virtio_driver {
struct device_driver driver;
const struct virtio_device_id *id_table;
const unsigned int *feature_table;
unsigned int feature_table_size;
int (*probe)(struct virtio_device *dev);
void (*scan)(struct virtio_device *dev);
void (*remove)(struct virtio_device *dev);
void (*config_changed)(struct virtio_device *dev);
#ifdef CONFIG_PM
int (*freeze)(struct virtio_device *dev);
int (*restore)(struct virtio_device *dev);
#endif
};

probescanremove 等等都是 I/O 驱动程序自己设置的函数指针。然后,内核可以为任何 I/O 驱动程序调用这些函数,而无需了解有关设备的任何信息。这是 C 中的抽象示例。参见 this article阅读有关此特定示例的更多信息。

另一种数据抽象形式是不透明指针。不透明数据类型在头文件中声明,但其定义从不公开。不知道类型定义的代码永远无法访问它的值,只能使用指向它的指针。参见 Opaque data typeOpaque pointer在维基百科上。

您可能遇到过的不透明数据类型的示例是 stdio.h 中的 FILE。所有操作系统都使用相同的接口(interface),尽管 FILE * 指向的实际数据不同。您可以通过调用 fopen 获取一个 FILE * 并使用一系列其他函数调用对其进行操作,但您可能看不到它指向的数据。

要了解有关 C 中面向对象编程的更多信息,我推荐免费的在线书籍 Object Oriented Programming in ANSI-C .查看this Dr Dobbs文章。相关问题:Object orientation in CCan you write object oriented code in C? .

关于c - C 中的数据抽象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com