用C编写面向对象代码有哪些方法?特别是在多态性方面。


另请参阅此堆栈溢出问题C中的面向对象。


我亲眼见过。我不推荐。c++最初是作为一个生成C代码的中间步骤的预处理器开始的。

本质上,您最终要做的是为所有方法创建一个调度表,其中存储函数引用。派生类需要复制这个分派表并替换您想要重写的条目,如果您的新“方法”想要调用基方法,则必须调用原始方法。最终,你要重写c++。


你可以使用函数指针来伪装它,事实上,我认为理论上可以将c++程序编译成C语言。

然而,将一种范式强加于一种语言,而不是选择一种使用范式的语言,很少有意义。


是的,但我从未见过有人尝试用C实现任何类型的多态性。


既然你说的是多态性,那么是的,你可以,我们在c++出现之前几年就已经在做这类事情了。

基本上,你使用一个结构体来保存数据和一个函数指针列表,以指向该数据的相关函数。

因此,在一个通信类中,你会有一个打开、读、写和关闭调用,它将被维护为结构中的四个函数指针,与对象的数据一起,类似于:

typedef struct {
    int (*open)(void *self, char *fspec);
    int (*close)(void *self);
    int (*read)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
    int (*write)(void *self, void *buff, size_t max_sz, size_t *p_act_sz);
    // And data goes here.
} tCommClass;

tCommClass commRs232;
commRs232.open = &rs232Open;
: :
commRs232.write = &rs232Write;

tCommClass commTcp;
commTcp.open = &tcpOpen;
: :
commTcp.write = &tcpWrite;

当然,上面的那些代码段实际上是在诸如rs232Init()这样的“构造函数”中。

当你“继承”这个类时,你只需要改变指针指向你自己的函数。每个调用这些函数的人都会通过函数指针来做,给你你的多态性:

int stat = (commTcp.open)(commTcp, "bigiron.box.com:5000");

有点像手动虚表。

你甚至可以通过将指针设置为NULL来创建虚拟类——这与c++的行为略有不同(运行时的核心转储而不是编译时的错误)。

下面是一段演示它的示例代码。首先是顶级类结构:

#include <stdio.h>

// The top-level class.

typedef struct sCommClass {
    int (*open)(struct sCommClass *self, char *fspec);
} tCommClass;

然后我们有TCP '子类'的函数:

// Function for the TCP 'class'.

static int tcpOpen (tCommClass *tcp, char *fspec) {
    printf ("Opening TCP: %s\n", fspec);
    return 0;
}
static int tcpInit (tCommClass *tcp) {
    tcp->open = &tcpOpen;
    return 0;
}

HTTP也是一样:

// Function for the HTTP 'class'.

static int httpOpen (tCommClass *http, char *fspec) {
    printf ("Opening HTTP: %s\n", fspec);
    return 0;
}
static int httpInit (tCommClass *http) {
    http->open = &httpOpen;
    return 0;
}

最后是一个测试程序来展示它的作用:

// Test program.

int main (void) {
    int status;
    tCommClass commTcp, commHttp;

    // Same 'base' class but initialised to different sub-classes.

    tcpInit (&commTcp);
    httpInit (&commHttp);

    // Called in exactly the same manner.

    status = (commTcp.open)(&commTcp, "bigiron.box.com:5000");
    status = (commHttp.open)(&commHttp, "http://www.microsoft.com");

    return 0;
}

这将产生输出:

Opening TCP: bigiron.box.com:5000
Opening HTTP: http://www.microsoft.com

你可以看到不同的函数被调用,取决于子类。


面向对象的C,可以做到,我在韩国看过这种类型的代码,这是我多年来见过的最可怕的怪物(这是去年(2007年)我看到的代码)。 所以,是的,这是可以做到的,是的,人们曾经这样做过,甚至在这个时代仍然这样做。但我还是推荐c++或Objective-C,这两种语言都起源于C,目的是用不同的范式提供面向对象。


是的。事实上,Axel Schreiner免费提供了他的书《ANSI-C中的面向对象编程》,这本书相当全面地涵盖了这个主题。


在Jim Larson 1996年在312节编程午餐研讨会上的演讲中有一个使用C进行继承的例子:高级和低级C。


当然这是可能的。这就是所有GTK+和GNOME所基于的框架GObject所做的工作。


是的,你可以。在c++或Objective-C出现之前,人们就开始编写面向对象的C语言了。在某种程度上,c++和Objective-C都试图采用C中使用的一些面向对象概念,并将它们形式化为语言的一部分。

这是一个非常简单的程序,它展示了如何创建一个看起来像方法调用的东西(有更好的方法可以做到这一点。这只是证明语言支持这些概念):

#include<stdio.h>

struct foobarbaz{
    int one;
    int two;
    int three;
    int (*exampleMethod)(int, int);
};

int addTwoNumbers(int a, int b){
    return a+b;
}

int main()
{
    // Define the function pointer
    int (*pointerToFunction)(int, int) = addTwoNumbers;

    // Let's make sure we can call the pointer
    int test = (*pointerToFunction)(12,12);
    printf ("test: %u \n",  test);

    // Now, define an instance of our struct
    // and add some default values.
    struct foobarbaz fbb;
    fbb.one   = 1;
    fbb.two   = 2;
    fbb.three = 3;

    // Now add a "method"
    fbb.exampleMethod = addTwoNumbers;

    // Try calling the method
    int test2 = fbb.exampleMethod(13,36);
    printf ("test2: %u \n",  test2);

    printf("\nDone\n");
    return 0;
}

动物和狗的小例子:你镜像了c++的虚表机制(基本上是这样)。你还分离了分配和实例化(Animal_Alloc, Animal_New),所以我们不会多次调用malloc()。我们还必须显式地传递this指针。

如果你要做非虚函数,那就很简单了。你只是不需要将它们添加到虚函数表中,静态函数也不需要this指针。多重继承通常需要多个虚表来解决歧义。

此外,您应该能够使用setjmp/longjmp来进行异常处理。

struct Animal_Vtable{
    typedef void (*Walk_Fun)(struct Animal *a_This);
    typedef struct Animal * (*Dtor_Fun)(struct Animal *a_This);

    Walk_Fun Walk;
    Dtor_Fun Dtor;
};

struct Animal{
    Animal_Vtable vtable;

    char *Name;
};

struct Dog{
    Animal_Vtable vtable;

    char *Name; // Mirror member variables for easy access
    char *Type;
};

void Animal_Walk(struct Animal *a_This){
    printf("Animal (%s) walking\n", a_This->Name);
}

struct Animal* Animal_Dtor(struct Animal *a_This){
    printf("animal::dtor\n");
    return a_This;
}

Animal *Animal_Alloc(){
    return (Animal*)malloc(sizeof(Animal));
}

Animal *Animal_New(Animal *a_Animal){
    a_Animal->vtable.Walk = Animal_Walk;
    a_Animal->vtable.Dtor = Animal_Dtor;
    a_Animal->Name = "Anonymous";
    return a_Animal;
}

void Animal_Free(Animal *a_This){
    a_This->vtable.Dtor(a_This);

    free(a_This);
}

void Dog_Walk(struct Dog *a_This){
    printf("Dog walking %s (%s)\n", a_This->Type, a_This->Name);
}

Dog* Dog_Dtor(struct Dog *a_This){
    // Explicit call to parent destructor
    Animal_Dtor((Animal*)a_This);

    printf("dog::dtor\n");

    return a_This;
}

Dog *Dog_Alloc(){
    return (Dog*)malloc(sizeof(Dog));
}

Dog *Dog_New(Dog *a_Dog){
    // Explict call to parent constructor
    Animal_New((Animal*)a_Dog);

    a_Dog->Type = "Dog type";
    a_Dog->vtable.Walk = (Animal_Vtable::Walk_Fun) Dog_Walk;
    a_Dog->vtable.Dtor = (Animal_Vtable::Dtor_Fun) Dog_Dtor;

    return a_Dog;
}

int main(int argc, char **argv){
    /*
      Base class:

        Animal *a_Animal = Animal_New(Animal_Alloc());
    */
    Animal *a_Animal = (Animal*)Dog_New(Dog_Alloc());

    a_Animal->vtable.Walk(a_Animal);

    Animal_Free(a_Animal);
}

PS.这是在c++编译器上测试的,但是在C编译器上运行应该很容易。


当然,它不会像使用带有内置支持的语言那样漂亮。我甚至写过“面向对象的汇编程序”。


如果您确信面向对象的方法对于您正在尝试解决的问题更优越,那么为什么还要尝试使用非面向对象的语言来解决它呢?看来你用错工具了。使用c++或其他面向对象的C语言变体。

如果你问这个问题是因为你要开始在一个已经存在的用C编写的大型项目上编写代码,那么你不应该试图将你自己的(或其他人的)OOP范式强加到项目的基础设施中。遵循项目中已经存在的指导方针。一般来说,干净的api和独立的库和模块将有助于实现干净的面向对象的设计。

如果,在所有这些之后,你真的打算做OOP C,请阅读这篇文章(PDF)。


看看GObject。它应该是C语言中的OO,是您正在寻找的东西的一个实现。如果你真的想要面向对象,那就使用c++或其他面向对象语言。如果您习惯了处理OO语言,那么GObject有时真的很难使用,但是像其他东西一样,您会习惯它的约定和流程。


你可能会发现,查看苹果的Core Foundation api集文档会很有帮助。它是一个纯C API,但是许多类型都被桥接到Objective-C对象等价物上。

看看Objective-C本身的设计也会有帮助。它与c++有点不同,对象系统是根据C函数定义的,例如objc_msg_send用于调用对象上的方法。编译器将方括号语法转换为这些函数调用,因此您不必了解它,但考虑到您的问题,您可能会发现了解它在底层是如何工作的很有用。


有几种技术可以使用。最重要的是如何分割项目。我们在项目中使用的接口是在.h文件中声明的,对象的实现是在.c文件中。重要的部分是,所有包含.h文件的模块都只将对象视为void *,而.c文件是唯一知道结构内部的模块。

以FOO类为例:

在。h文件中

#ifndef FOO_H_
#define FOO_H_

...
 typedef struct FOO_type FOO_type;     /* That's all the rest of the program knows about FOO */

/* Declaration of accessors, functions */
FOO_type *FOO_new(void);
void FOO_free(FOO_type *this);
...
void FOO_dosomething(FOO_type *this, param ...):
char *FOO_getName(FOO_type *this, etc);
#endif

C实现文件就像这样。

#include <stdlib.h>
...
#include "FOO.h"

struct FOO_type {
    whatever...
};


FOO_type *FOO_new(void)
{
    FOO_type *this = calloc(1, sizeof (FOO_type));

    ...
    FOO_dosomething(this, );
    return this;
}

因此,我明确地将指针指向该模块的每个函数。c++编译器隐式地完成它,而在C中我们显式地将它写出来。

我真的在我的程序中使用了这个,以确保我的程序不是用c++编译的,而且它在我的语法高亮编辑器中有另一种颜色的良好属性。

FOO_struct的字段可以在一个模块中修改,而另一个模块甚至不需要重新编译就仍然可用。

通过这种风格,我已经处理了OOP(数据封装)的很大一部分优点。通过使用函数指针,甚至可以很容易地实现继承之类的东西,但老实说,它真的很少有用。


命名空间通常通过以下方式实现:

stack_push(thing *)

而不是

stack::push(thing *)

要将C结构体变成类似c++类的东西,您可以转向:

class stack {
     public:
        stack();
        void push(thing *);
        thing * pop();
        static int this_is_here_as_an_example_only;
     private:
        ...
};

Into

struct stack {
     struct stack_type * my_type;
     // Put the stuff that you put after private: here
};
struct stack_type {
     void (* construct)(struct stack * this); // This takes uninitialized memory
     struct stack * (* operator_new)(); // This allocates a new struct, passes it to construct, and then returns it
     void (*push)(struct stack * this, thing * t); // Pushing t onto this stack
     thing * (*pop)(struct stack * this); // Pops the top thing off the stack and returns it
     int this_is_here_as_an_example_only;
}Stack = {
    .construct = stack_construct,
    .operator_new = stack_operator_new,
    .push = stack_push,
    .pop = stack_pop
};
// All of these functions are assumed to be defined somewhere else

和做的事:

struct stack * st = Stack.operator_new(); // Make a new stack
if (!st) {
   // Do something about it
} else {
   // You can use the stack
   stack_push(st, thing0); // This is a non-virtual call
   Stack.push(st, thing1); // This is like casting *st to a Stack (which it already is) and doing the push
   st->my_type.push(st, thing2); // This is a virtual call
}

我没有做析构函数或删除,但它遵循相同的模式。

This_is_here_as_an_example_only类似于一个静态类变量——在一个类型的所有实例之间共享。所有的方法都是静态的,除了一些采用this *


您可能需要做的一件事是研究X Window的Xt工具包的实现。当然,它已经很老了,但是许多使用的结构都是在传统的c语言中以面向对象的方式设计的。一般来说,这意味着在这里或那里添加一个额外的间接层,并设计相互覆盖的结构。

你真的可以在C语言中以面向对象的方式做很多事情,即使有时感觉,面向对象的概念并没有完全从#include<favorite_OO_Guru.h>的思想中涌现出来。它们确实构成了当时许多公认的最佳实践。面向对象语言和系统只是提炼和放大了当时编程时代精神的一部分。


我认为首先要说的是(至少在我看来)C的函数指针实现真的很难使用。我会跳过一大堆的圆环来避免函数指针…

也就是说,我认为其他人说的很好。你有结构,你有模块,而不是foo->方法(a,b,c),你最终用方法(foo,a,b,c)如果你有一个“method”方法,那么你可以用类型前缀它,所以FOO_method(foo,a,b,c),正如其他人所说…通过良好地使用.h文件,您可以获得私有和公共文件,等等。

现在,有一些事情是这个技巧不能给你的。它不会提供私有数据字段。我认为,这与意志力和良好的编码习惯有关……而且,没有一种简单的方法来继承它。

这些至少是简单的部分……其余的,我认为是90/10的情况。10%的收益需要90%的工作……


我相信,用C语言实现OOP除了本身很有用外,还是学习OOP和理解其内部工作原理的好方法。许多程序员的经验表明,要有效和自信地使用一项技术,程序员必须理解底层概念最终是如何实现的。在C语言中模拟类、继承和多态性就教会了我们这一点。

为了回答最初的问题,这里有一些资源,教如何在C中进行OOP:

embeddegurus.com博客文章“C中基于对象的编程”展示了如何在可移植C中实现类和单继承: http://embeddedgurus.com/state-space/2008/01/object-based-programming-in-c/

应用笔记“C+ - C面向对象编程”展示了如何使用预处理器宏在C中实现类、单继承和后期绑定(多态性): http://www.state-machine.com/resources/cplus_3.0_manual.pdf,示例代码可从http://www.state-machine.com/resources/cplus_3.0.zip获得


哪些文章或书籍适合在C语言中使用面向对象的概念?

Dave Hanson的《C接口与实现》在封装和命名方面非常出色,在函数指针的使用方面也非常出色。Dave没有尝试模拟继承。


C的stdio FILE子库是如何在纯C中创建抽象、封装和模块化的极好示例。

继承和多态性——通常被认为是OOP必不可少的其他方面——不一定能提供它们所承诺的生产率提高,而且有合理的理由认为它们实际上会阻碍开发和对问题域的思考。


我建议使用Objective-C,它是C的超集。

虽然Objective-C已经有30年的历史了,但它允许编写优雅的代码。

http://en.wikipedia.org/wiki/Objective-C


这本书读起来很有趣。我自己也在思考同样的问题,思考这个问题的好处是:

Trying to imagine how to implement OOP concepts in a non-OOP language helps me understand the strengths of the OOp language (in my case, C++). This helps give me better judgement about whether to use C or C++ for a given type of application -- where the benefits of one out-weighs the other. In my browsing the web for information and opinions on this I found an author who was writing code for an embedded processor and only had a C compiler available: http://www.eetimes.com/discussion/other/4024626/Object-Oriented-C-Creating-Foundation-Classes-Part-1

在他的案例中,用普通C语言分析和调整面向对象的概念是一种有效的追求。他似乎愿意牺牲一些面向对象的概念,因为尝试用C语言实现它们会带来性能开销。

我得到的教训是,是的,在某种程度上它是可以做到的,是的,有一些很好的理由去尝试。

In the end, the machine is twiddling stack pointer bits, making the program counter jump around and calculating memory access operations. From the efficiency standpoint, the fewer of these calculations done by your program, the better... but sometimes we have to pay this tax simply so we can organize our program in a way that makes it least susceptible to human error. The OOP language compiler strives to optimize both aspects. The programmer has to be much more careful implementing these concepts in a language like C.


添加一点OOC代码:

#include <stdio.h>

struct Node {
    int somevar;
};

void print() {
    printf("Hello from an object-oriented C method!");
};

struct Tree {
    struct Node * NIL;
    void (*FPprint)(void);
    struct Node *root;
    struct Node NIL_t;
} TreeA = {&TreeA.NIL_t,print};

int main()
{
    struct Tree TreeB;
    TreeB = TreeA;
    TreeB.FPprint();
    return 0;
}

我已经研究这个一年了

由于GObject系统很难用纯C语言使用,所以我尝试编写一些不错的宏来简化C语言的OO风格。

#include "OOStd.h"

CLASS(Animal) {
    char *name;
    STATIC(Animal);
    vFn talk;
};
static int Animal_load(Animal *THIS,void *name) {
    THIS->name = name;
    return 0;
}
ASM(Animal, Animal_load, NULL, NULL, NULL)

CLASS_EX(Cat,Animal) {
    STATIC_EX(Cat, Animal);
};
static void Meow(Animal *THIS){
    printf("Meow!My name is %s!\n", THIS->name);
}

static int Cat_loadSt(StAnimal *THIS, void *PARAM){
    THIS->talk = (void *)Meow;
    return 0;
}
ASM_EX(Cat,Animal, NULL, NULL, Cat_loadSt, NULL)


CLASS_EX(Dog,Animal){
    STATIC_EX(Dog, Animal);
};

static void Woof(Animal *THIS){
    printf("Woof!My name is %s!\n", THIS->name);
}

static int Dog_loadSt(StAnimal *THIS, void *PARAM) {
    THIS->talk = (void *)Woof;
    return 0;
}
ASM_EX(Dog, Animal, NULL, NULL, Dog_loadSt, NULL)

int main(){
    Animal *animals[4000];
    StAnimal *f;
    int i = 0;
    for (i=0; i<4000; i++)
    {
        if(i%2==0)
            animals[i] = NEW(Dog,"Jack");
        else
            animals[i] = NEW(Cat,"Lily");
    };
    f = ST(animals[0]);
    for(i=0; i<4000; ++i) {
        f->talk(animals[i]);
    }
    for (i=0; i<4000; ++i) {
        DELETE0(animals[i]);
    }
    return 0;
}

这是我的项目网站(我没有足够的时间写en。Doc,不过中文的Doc要好得多)。

东方海外海湾合作委员会


OOP只是一个范例,在程序中数据比代码更重要。OOP不是一种语言。因此,就像普通C是一种简单的语言一样,普通C中的OOP也很简单。


这个问题的答案是“是的,你可以”。

面向对象的C (OOC)工具包是为那些希望以面向对象的方式进行编程的人准备的,但它也沿用了优秀的老C。OOC实现了类、单继承和多继承、异常处理。

特性

•只使用C宏和函数,不需要语言扩展!(ansi c)

•易于阅读的源代码为您的应用程序。小心翼翼地使事情尽可能简单。

•类的单一继承

•通过接口和mixin进行多重继承(从1.3版开始)

•实现异常(纯C!)

•类的虚函数

•易于类实现的外部工具

欲了解更多详情,请访问http://ooc-coding.sourceforge.net/。


关于c语言OOP的另一个变化,请参阅http://slkpg.byethost7.com/instance.html。它强调仅使用本机c实现实例数据的可重入性,多重继承使用函数包装器手动完成。保持型号安全。下面是一个小例子:

typedef struct _peeker
{
    log_t     *log;
    symbols_t *sym;
    scanner_t  scan;            // inherited instance
    peek_t     pk;
    int        trace;

    void    (*push) ( SELF *d, symbol_t *symbol );
    short   (*peek) ( SELF *d, int level );
    short   (*get)  ( SELF *d );
    int     (*get_line_number) ( SELF *d );

} peeker_t, SlkToken;

#define push(self,a)            (*self).push(self, a)
#define peek(self,a)            (*self).peek(self, a)
#define get(self)               (*self).get(self)
#define get_line_number(self)   (*self).get_line_number(self)

INSTANCE_METHOD
int
(get_line_number) ( peeker_t *d )
{
    return  d->scan.line_number;
}

PUBLIC
void
InitializePeeker ( peeker_t  *peeker,
                   int        trace,
                   symbols_t *symbols,
                   log_t     *log,
                   list_t    *list )
{
    InitializeScanner ( &peeker->scan, trace, symbols, log, list );
    peeker->log = log;
    peeker->sym = symbols;
    peeker->pk.current = peeker->pk.buffer;
    peeker->pk.count = 0;
    peeker->trace = trace;

    peeker->get_line_number = get_line_number;
    peeker->push = push;
    peeker->get = get;
    peeker->peek = peek;
}

是的,这是可能的。

这是纯C语言,没有宏预处理。它具有继承、多态、数据封装(包括私有数据)。它没有等效的受保护限定符,这意味着私有数据在整个继承链中也是私有的。

#include "triangle.h"
#include "rectangle.h"
#include "polygon.h"

#include <stdio.h>

int main()
{
    Triangle tr1= CTriangle->new();
    Rectangle rc1= CRectangle->new();

    tr1->width= rc1->width= 3.2;
    tr1->height= rc1->height= 4.1;

    CPolygon->printArea((Polygon)tr1);

    printf("\n");

    CPolygon->printArea((Polygon)rc1);
}

/*output:
6.56
13.12
*/

似乎人们正在尝试用C来模仿c++风格。我的观点是,用C来做面向对象的编程实际上就是做面向结构的编程。但是,您可以实现后期绑定、封装和继承等功能。对于继承,在子结构中显式地定义一个指向基结构的指针,这显然是一种多重继承。你还需要确定你的

//private_class.h
struct private_class;
extern struct private_class * new_private_class();
extern int ret_a_value(struct private_class *, int a, int b);
extern void delete_private_class(struct private_class *);
void (*late_bind_function)(struct private_class *p);

//private_class.c
struct inherited_class_1;
struct inherited_class_2;

struct private_class {
  int a;
  int b;
  struct inherited_class_1 *p1;
  struct inherited_class_2 *p2;
};

struct inherited_class_1 * new_inherited_class_1();
struct inherited_class_2 * new_inherited_class_2();

struct private_class * new_private_class() {
  struct private_class *p;
  p = (struct private_class*) malloc(sizeof(struct private_class));
  p->a = 0;
  p->b = 0;
  p->p1 = new_inherited_class_1();
  p->p2 = new_inherited_class_2();
  return p;
}

    int ret_a_value(struct private_class *p, int a, int b) {
      return p->a + p->b + a + b;
    }

    void delete_private_class(struct private_class *p) {
      //release any resources
      //call delete methods for inherited classes
      free(p);
    }
    //main.c
    struct private_class *p;
    p = new_private_class();
    late_bind_function = &implementation_function;
    delete_private_class(p);

用c_compiler main.c inherited_class_1编译。obj inherited_class_2。obj private_class.obj。

因此,我的建议是坚持使用纯C风格,不要试图强行采用c++风格。此外,这种方式也有助于以一种非常干净的方式构建API。


我有点晚了,但我想分享我在这个主题上的经验:我这些天在使用嵌入式的东西,我唯一的(可靠的)编译器是C,所以我想在我用C编写的嵌入式项目中应用面向对象的方法。

到目前为止,我看到的大多数解决方案都大量使用类型转换,因此我们失去了类型安全:如果你犯了错误,编译器不会帮助你。这是完全不能接受的。

我的要求是:

尽可能避免类型转换,这样我们就不会失去类型安全; 多态:我们应该能够使用虚方法,类的用户不应该知道某个特定的方法是否是虚的; 多重继承:我不经常使用它,但有时我确实希望某个类实现多个接口(或扩展多个超类)。

我在本文中详细解释了我的方法:C语言中的面向对象编程;另外,还有一个工具可以自动生成基类和派生类的样板代码。


我建立了一个小图书馆,在那里我尝试了,对我来说,它真的很有效。所以我想和你分享这段经历。

https://github.com/thomasfuhringer/oxygen

使用结构并将其扩展到每个其他子类,可以很容易地实现单继承。对父结构进行简单的强制转换,就可以在所有后代上使用父方法。 只要知道变量指向持有此类对象的结构体,就可以始终将其转换为根类并进行自省。

正如前面提到的,虚拟方法有点棘手。但它们是可行的。为了保持简单,我只是在类描述结构中使用了一个函数数组,每个子类在需要的地方复制和重新填充单独的插槽。

多重继承实现起来相当复杂,并且会对性能产生重大影响。所以我离开了。我确实认为,在相当多的情况下,清晰地模拟现实生活环境是可取和有用的,但在可能90%的情况下,单一继承可以满足需求。而且单一继承很简单,没有成本。

我也不关心类型安全。我认为你不应该依赖编译器来防止你的编程错误。而且无论如何,它只能保护您避免相当小部分的错误。

通常,在面向对象的环境中,您还希望实现引用计数以尽可能地自动化内存管理。因此,我还在“Object”根类中放入了引用计数,并使用了一些功能来封装堆内存的分配和释放。

它非常简单和精简,给了我OO的基本要领,而不强迫我去处理c++这个怪物。而且我保留了留在C领域的灵活性,这使得集成第三方库更加容易。