多态性(C语言) [英] Polymorphism (in C)

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

问题描述

可能重复:结果
  我如何可以模拟OO风格多态性C 2

我想更好地了解基因多态性与我知道的例子语言的想法;
有多态性用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\n", kitty.name, animal_sound(&kitty));
    printf("%s says %s\n", lassie.name, animal_sound(&lassie));

    return 0;
}

这是运行时多态性的例子当方法解析碰巧的。

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

C1X增加通用的选择,这使得通过宏可能编译时多态。下面的例子是从C1X四月草案采取部分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天全站免登陆