c - 将 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 继承如何转化为程序化?你觉得程序如何?
解决方案
你的想法导致函数指针绝对是正确的方法。
这个想法是我们有“父”类的函数指针,子类带有指向该父结构的指针,当我们定义自己的函数定义时,我们可以将这些函数指向我们实现的函数。
我将为您粗略地举一个简单的例子来说明如何实现这一点。
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);
}
推荐阅读
- aerospike - Aerospike:一级和二级索引如何在内部工作
- roku - Roku:在网格屏幕的频道标志下显示每个项目的频道名称
- java - 具有生成实体的验证器持久化
- android - 视图设计问题:如何使滚动视图的子视图填充屏幕?
- cassandra - 无法建立连接,所有主机尝试查询失败
- ios - 如何在 ios 中使用应用隐藏式字幕设置而不是系统隐藏式字幕设置
- php - 使用 PHP 下载带有警告框的文件
- winapi - 如何管理任务栏上的应用程序图标?
- c# - System.Data.EvaluateException HResult=0x80131920 消息=无法对 System.Int32 和 System.String 执行“=”操作
- java - 如何使 Result Scan Barcode 与 Data Retrofit 匹配?