多态性(在 C 中) [英] Polymorphism (in C)

查看:17
本文介绍了多态性(在 C 中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何在 C 中模拟 OO 风格的多态性?

我试图通过我所知道的语言中的示例来更好地理解多态性的概念;C语言中是否存在多态性?

I'm trying to better understand the idea of polymorphism with examples from languages I know; is there polymorphism in C?

推荐答案

这是 Nekuromento 的第二个例子,考虑到我认为面向对象 C 的惯用方式:

This is Nekuromento's second example, factored in the way I consider idiomatic for object-oriented C:

#ifndef ANIMAL_H_
#define ANIMAL_H_

struct animal
{
    // make vtable_ a pointer so they can be shared between instances
    // use _ to mark private members
    const struct animal_vtable_ *vtable_;
    const char *name;
};

struct animal_vtable_
{
    const char *(*sound)(void);
};

// wrapper function
static inline const char *animal_sound(struct animal *animal)
{
    return animal->vtable_->sound();
}

// make the vtables arrays so they can be used as pointers
extern const struct animal_vtable_ CAT[], DOG[];

#endif

cat.c

#include "animal.h"

static const char *sound(void)
{
    return "meow!";
}

const struct animal_vtable_ CAT[] = { { sound } };

dog.c

#include "animal.h"

static const char *sound(void)
{
    return "arf!";
}

const struct animal_vtable_ DOG[] = { { sound } };

main.c

#include "animal.h"
#include <stdio.h>

int main(void)
{
    struct animal kitty = { CAT, "Kitty" };
    struct animal lassie = { DOG, "Lassie" };

    printf("%s says %s
", kitty.name, animal_sound(&kitty));
    printf("%s says %s
", lassie.name, animal_sound(&lassie));

    return 0;
}

这是一个运行时多态性的例子,因为那是方法解析发生的时候.

This is an example of runtime polymorphism as that's when method resolution happens.

C1x 添加了泛型选择,这使得通过宏实现编译时多态性成为可能.以下示例摘自 C1x 4 月草案,第 6.5.1.1 节第 5 节:

C1x added generic selections, which make compile-time polymorphism via macros possible. The following example is taken from the C1x April draft, section 6.5.1.1 §5:

#define cbrt(X) _Generic((X), 
    long double: cbrtl, 
    default: cbrt, 
    float: cbrtf 
)(X)

用于数学函数的类型通用宏已经在 C99 中通过头文件 tgmath.h 提供,但用户无法在不使用编译器扩展的情况下定义自己的宏.

Type-generic macros for math functions were already available in C99 via the header tgmath.h, but there was no way for users to define their own macros without using compiler extensions.

这篇关于多态性(在 C 中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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