【问题标题】:C language also supports abstraction? [duplicate]C语言也支持抽象? [复制]
【发布时间】:2021-06-28 20:28:19
【问题描述】:

根据抽象的定义,隐藏内部代码的实现,这可以通过 OOP 语言通过提供方法和属性绑定到该对象的类对象来实现。 我的问题是......如果用 C 语言编写一些函数并将其原型和返回类型共享给开发人员以供使用,那么我也可以实现抽象。

那么为什么抽象是面向对象语言的特性而不是面向过程的语言呢??

【问题讨论】:

  • 你可以用C写面向对象的代码。确实没有什么特殊的语法,但是OOP是一套思想,不是特定的语法或一组关键字。
  • 如果我是对的,C++ 的第一个版本是用 C 语言编写的,使用宏。
  • @YvesDaoust Cfront,第一个 C++ 实现,是一个生成 C 代码作为输出的编译器。
  • @skrrgwasme 还不是我,但我很受诱惑。 为什么抽象是 OOP 而不是过程语言的一个特征 有很多解释和潜在的争论。某些类型的抽象显然是 C++、Java 和 Swift 等语言的设计特性;即使您可以使用它的构建块来实现抽象,C 也没有任何特定的支持(有点)。另一方面,包括汇编在内的每一种计算机语言都是一种隐藏细节的抽象。此外,这个问题是基于对程序语言的毫无根据的假设。
  • @0___________ 听起来我的评论中有一些你不同意的地方,但我不知道它可能是什么。我是在回复之前的评论,而不是针对问题。

标签: c oop


【解决方案1】:

听起来您的“抽象”定义过于受限。

您关于“抽象”可以通过过程编程语言实现的结论是正确的。用 C 编写的驱动程序提供了一种抽象,允许操作系统在不知道细节的情况下与硬件进行交互。 Python 抽象了字典的实现细节(在 C 中实现)以允许程序员轻松使用它们。踏板和方向盘提供了操作机动车辆的简单抽象。

抽象并不局限于 OOP,它只是在教授 OOP 时重点强调的一方面。

如果您从提供“抽象定义”的参考资料中学习,这意味着它仅适用于 OOP,我建议您寻找新资源,因为这不正确。

【讨论】:

    【解决方案2】:

    尽管 C 不是为支持面向对象编程而设计的,但仍然可以用 C 编写 OOP(或更准确地说,使用 C 特性实现 OOP 概念)。

    一种常见的方法是将结构用作“对象” - Data Abstraction in C (@jacwah)

    查看下面 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
    };
    

    另一种方法是通过命名约定和正确使用模块 - http://rodrigomendez.me/writing-object-oriented-code-in-c/

    还请看(参考有关该主题的书)- How would one write object-oriented code in C?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2023-02-23
      • 2011-11-08
      • 2018-03-17
      相关资源
      最近更新 更多