首页 > 解决方案 > 将 C++ OO 层次结构转换为 C 过程

问题描述

我已经使用 C 有一段时间了,但有时当我想到如何解决问题时,我似乎想不出任何其他方式,只能以 OO 方式,就像我在学校所教的那样。由于我一直在使用 C,我主要使用的是 OO 模式,但在 C 中,有时会与语言对抗以使其工作。举一个简单的例子,如果我需要编写一个文件系统资源抽象,我会考虑编写一个 Resource 基类,它会被 ImageFile 类和 AudioFile 类继承。

class Resource {
    bool opened;
    virtual bool load_file(const char *fpath);
    virtual bool release(void);
}

class ImageFile : Resource {
    bool load_file(const char *fpath) { ... }
    bool release(const char *fpath) { ... }
}

class AudioFile : Resource {
    bool load_file(const char *fpath) { ... }
    bool release(const char *fpath) { ... }
}

int main() {
    Resource img = ImageFile();
    Resource mus = AudioFile();

    img.load_file("my_image.png");
    mus.load_file("song.mp3");

    img.release();
    mus.release();

    return 0;
}

在 C 中,我使用函数指针来复制这种行为。问题是,那仍然是面向对象的设计,我想学习程序化思考。你将如何以程序化的方式设计同样的问题?OO 继承如何转化为程序化?你觉得程序如何?

标签: coopprocedural

解决方案


你的想法导致函数指针绝对是正确的方法。

这个想法是我们有“父”类的函数指针,子类带有指向该父结构的指针,当我们定义自己的函数定义时,我们可以将这些函数指向我们实现的函数。

我将为您粗略地举一个简单的例子来说明如何实现这一点。

struct resource {
    bool (*load_file)(const char *fpath);
    bool (*release)(const char *fpath)
};

struct imageFile {
    struct resource *ops;
};

struct audioFile {
    struct resource *ops;
};

bool image_load_file(const char *fpath) {...}
bool image_release(const char *fpath) {...}

bool audio_load_file(const char *fpath) {...}
bool audio_release(const char *fpath) {...}

int main () {
    static const struct op1 = {
        image_load_file,
        image_release,
    };

    static const struct op2 = {
        audio_load_file,
        audio_release,
    };

    // Assigning the functon pointers

    struct imageFile *im = malloc(sizeof(*im));
    im->ops = op1;

    struct audioFile *aud = malloc(sizeof(*aud));
    aud->ops = op2;

    // Calling the functions
    im->ops->load_file(fpath);
    im->ops->release(fpath);
}

推荐阅读