注册 登录
编程论坛 C++教室

[讨论]在C中实现面向对象

百年不亮 发布于 2007-09-11 19:25, 471 次点击
下面是我模仿C++中的vector用C写的一个类的定义,希望大家不要说我吃饱饭没事干,我只想研究下C中使用面向对象思想可以写出什么样子的程序。原帖发于C区没人睬所以在这里转发,原帖地址:https://bbs.bc-cn.net/viewthread.php?tid=168963

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

//=============================Starting to define my Array class=========================

//-----------------------------Declaration segment-------------------------
typedef int DataType;
typedef struct array{

    DataType    *Data;
    int size,max_size;
        
    void (*Input)(DataType , struct array *);
    void (*Constructor)(struct array *);
    void (*Destructor)(struct array *);        
}Array;

void Init(Array *this);
void _constructor(Array *this);
void _denstructor(Array *this);
void _input(DataType data, Array *this);

//------------------------------Implemen segment---------------------------

void _input(DataType data, Array *this)
{
    int i;
    DataType *ptr;
     
    if(this->size >= this->max_size)
    {
        this->max_size +=10;
        ptr=(DataType *)malloc(this->max_size*sizeof(DataType));
        
        for(i=0;i<this->size;i++)
            ptr[i]=this->Data[i];   

        free(this->Data);
        this->Data=ptr;
    }     
         
    this->Data[this->size]=data;
    ++(this->size);     
}
        
        
void _constructor(Array *this)
{
    this->size=0;
    this->max_size=10;
    this->Data=(DataType *)malloc(this->max_size*sizeof(DataType));
}

void _denstructor(Array *this)
{
    free(this->Data);
}


void Init(Array *this)
{
    this->Input =_input;
    this->Constructor =_constructor;
    this->Destructor =_denstructor;

    this->Constructor(this);
}

//===================================definition end===============================


// 使用示例
int main()
{
    Array MyArray;
    Init(&MyArray);            //使用对象前必须初始化,间接调用构造函数

    MyArray.Input(1,&MyArray);
    MyArray.Input(2,&MyArray);

    printf(\"The elements of MyArray :  %d,\t%d\",MyArray.Data[0],MyArray.Data[1]);
    getch();

    MyArray.Destructor(&MyArray);    //使用对象后必须显式调用析构函数

    return 0;
   
}


如果大家可以用C写出更加OO的code欢迎跟贴讨论。

[此贴子已经被作者于2007-9-11 19:28:11编辑过]

1 回复
#2
aipb20072007-09-11 22:28
你怎么觉得这是面向对象的呢?

还有,和vector的实现差别还是有点大哦!



不过模块很清晰哈!
1