Chinaunix首页 | 论坛 | 博客
  • 博客访问: 187722
  • 博文数量: 28
  • 博客积分: 1490
  • 博客等级: 上尉
  • 技术积分: 310
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-17 10:01
文章分类
文章存档

2012年(3)

2011年(2)

2008年(2)

2007年(7)

2006年(14)

我的朋友

分类: C/C++

2006-10-20 13:54:05

Inside Object-Oriented Programming Using ANSI C
系列之一

C++ 中信息的隐藏与封装是通过 namespaceclass 来实现的,通常模块之间是以类为基础来构建的。然而,在 C 中,模块是通过文件来构建的,C 中文件的独立性可以与 C++ 中 namespace 等同,通常地,在 C 中,我们也可以将独立的文件相当于 C++ 中的 class

对于 class 来说,存在其对应的属性和方法。比如:

class Flower
{
public:
    Flower(int color);
    virtual ~Flower();
public:
    void Blow(void);
    void SetColor(int color);
    float GetColor(void);
    << ... >>
private:
    int m_nColor;
    << ... >>
 
}


相应地,在 C 中,我们可以这样来实现以上对应的片断:


/* file: flower.c */

#include <stdio.h>

static int _hb_color = 0.0f;

void
flower_set_color(int color)
{
    _hb_color = color;
}

int
flower_get_color(void)
{
    return _hb_color;
}

void
flower_blow(void)
{
    printf("listen, the flower's blowing voice ... \n");
}


这里,我们在 C 中隐藏信息用的是静态变量声明 static ,这样,我们避免了文件间变量的同名,这与 namespace/class 的作用是一致的,同时,用 static 声明的变量或函数相当于 class 中的 privateprotected 声明的变量或函数,外部是无法直接调用的。说明:为了区别于局部变量,我将静态变量名加上了特别的前缀 _hb_ 以示区别,增强了程序的可读性。但这样存在一个严重的问题,那就是你无法在 C 中构建多个 Flower 的对象,因为他们都共享着同一个变量。接着而来的问题是,如果我们新建类 Rose 继承自 Flower,在C++中,很好实现,但我们该怎么在 C 中对应呢?


class Rose : public Flower
{

public:

    Rose(int nThorn);

    virtual ~Rose();
<< ... >>
public:

    void SetThornNumber(int nThorn);
    int GetThornNumber();
private:
    int m_nThorn;
}


我们可以通过一定的途径来达到一定的效果,但这个方式无法解决以上的问题。


/* flower.c */

<<< ... >>>

static int _hb_thorn = 1;

void
rose_set_color(int color)
{
    flower_set_color(color);
}

int
rose_get_color(void)
{
    return 
flower_get_color();
}

void
rose_blow(void)
{
    printf("listen, rose is blowing, and your lover is coming ... \n");
}

void
rose_set_thorn_nr(int thorn)
{
    _hb_thorn = thorn;
}

int

rose_get_thorn_nr(void)
{
    return _hb_thorn;
}


这里面的缺陷是显而易见的,但也多少展现了一丁点儿的封装的意思。可以说这里面的数据和实现是严严实实地捆绑在一起,我们需要一种机制来将他们分离。
阅读(1667) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~