woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

有点意思struct代码设计

用数组+指针+半面向对象(C)或 集合+指针+CLASS(C++)。
具体可以参考GTK+的代码,这里举一个简单的例子:

#include <stdio.h>
#include <stdlib.h>
enum{
    STRUCT_S1,
    STRUCT_S2
};
struct base{
    const int type;
};
struct s1{
    const int type;//必须位于第一个。
    int abc;
    int def;
};
struct s2{
    const int type;//必须位于第一个。
    long jsk;
    char abcde[10];
};
int main()
{
    void * a[10]={0};
    struct s1 b={STRUCT_S1, 1, 2};
    struct s2 c={STRUCT_S2, 111, "123"};
    a[0] = &b;
    a[1] = &c;
    int i;
    for(i=0; i<10; i++)
    {
        struct base * base;
        if(base = a[i])
        {
            switch(base->type){
                case STRUCT_S1:
                    {
                        struct s1 *p = a[i];
                        printf("%d %d\n", p->abc, p->def);
                    }
                    break;
                case STRUCT_S2:
                    {
                        struct s2 *p = a[i];
                        printf("%ld %s\n", p->jsk, p->abcde);
                    }
                    break;
            }
        }
    }
    return 0;
}

posted on 2008-11-11 10:21 肥仔 阅读(319) 评论(0)  编辑 收藏 引用 所属分类: C++ 基础


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理