用C派生类 - 什么是你最喜欢的方法是什么? [英] Derived classes in C - What is your favorite method?

查看:111
本文介绍了用C派生类 - 什么是你最喜欢的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的面向对象的C语言编程的经验,我已经看到了两种方法来实现派生类。

In my experience in object oriented C programming I have seen two ways to implement derived classes.


第一种方法,有父类的定义为.h文件。然后,每个从这个类派生类将有做的:

First Method, have a definition of the parent class as a .h file. Then each class that derives from this class will have do:

文件par​​ent_class.h:

File parent_class.h:

int member1;
int member2;

文件testing.c:

File testing.c:

struct parent_class {
    #include "parent_class.h" // must be first in the struct
}

struct my_derived_class {
    #include "parent_class.h" // must be first in the struct
    int member3;
    int member4;
}



第二法,会做:

文件testing.c:

File testing.c:

struct parent_class {
    int member3;
    int member4;
}

struct my_derived_class {
    struct parent_class; // must be first in the struct
    int member3;
    int member4;
}



什么是你最喜欢用C做的派生类的方法(不必是我做了什么)?为什么?

What is your favorite method of doing derived classes in C ( doesn't have to be what I have done )? and why?

哪种方法你会preFER,第一个或第二个方法(或你自己的)?

Which method would you prefer, first or second method ( or your own )?

推荐答案

我使用方法2.作品一样好方法1库的维护者之一,但没有任何preprocessor挂羊头卖狗肉。或者它实际上工作得更好,因为你可以有把基类参数的函数,你可以直接转换为基本结构,C保证这个工程的第一个成员。

I'm one of the maintainers of a library that uses method 2. Works just as well as method 1, but without any preprocessor trickery. Or it actually works better, since you can have functions that take the base class as argument and you can just cast to the base struct, C guarantees that this works for the first member.

更有趣的问题是,你怎么办虚函数?在我们的例子中,结构有指向所有功能,并且初始化设置它们。这是稍微简单,但有更多的空间开销比取之有道的指针到一个共享的虚函数表。

The more interesting question is, how do you do virtual functions? In our case, the struct has pointers to all the functions, and the initialization set them up. It's slightly simpler, but has more space overhead than the "proper way" with a pointer to a shared vtable.

不过,我还是preFER使用C ++而不是普通的C杂牌组装电脑,但政治..

Anyway, I'd prefer to use C++ rather than kludge it with plain C, but politics..

这篇关于用C派生类 - 什么是你最喜欢的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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