C, C++, Object C 初步比较

这个周末终于忍不住学了一下OC,到今天为止,OC的语法总算过了一遍,调用方式大致也了解了,下面就来比较一下OC,C,C++的不同。

————————————————————————–

OC的语法如下:

//shape.h
@interface shape

- (void) set_color: (int) cl;
- (void) draw;

@end

//shap.m
@implementation shape
{
int color;
}

- (void) set_color: (int) cl
{
color = cl;
}

- (void) do_stuff
{
color++;
}
- (void) draw
{
[self do_stuff];
printf("draw shape, color:%dn", color);
}
@end

//main.m
int main(int argc, const char *argv[])
{
shape *p;

p = [[shape alloc] init];
[p set_color: 3];
[p draw];

return 0;
}

C语法如下:

//shape.h
struct shape * shape_create(void);
void set_color(struct shape *self, int color);
void draw(struct self);

//shape.c
#include
struct shape {
int shape;
};

struct shape_create()
{
struct shape *p = (struct shape *)malloc(sizeof(struct shape));

return p;
}

void set_color(struct shape *self, int color)
{
self->color = color;
}

static void do_stuff(struct shape *self)
{
self->color++;
}

void draw(struct shape *self)
{
do_stuff(self);
printf("draw shape, color:%dn", self->color);
}

//main.c
int main(int argc, const char *argv[])
{
struct shape *p;

p = shape_create();

set_color(p, 3);
draw(p);

return 0;
}


C++的语法如下:

//shape.h
class shape {
private:
int color;
private:
void do_stuff(void);
public:
void set_color(int color);
void draw(void);
}
//shape.cpp
void shape::do_stuff(void)
{
color++;
}

void shape::set_color(int cl)
{
color = cl;
}

void shape::draw()
{
do_stuff();
printf("draw shape, color:%dn", self->color);
}

//main.cpp
int main(int argc, const char *argv[])
{
class shape *p;

p = new shape;

p->set_color(3);
p->draw();

return 0;
}


————————————————————————–
1. 关于接口与现分离
从代码上可以看出,do_stuff函数与color变量是类或模块自己内部使用,因此从理论上来说不应该导出到头文件中,这个不符合高内聚原则,下面看一下C, C++, Object C分别是如何实现的:
@C 可以看到在C中,完全可以隐藏color变量与do_stuff这个内部函数,
客户程序从头文件中不会知道do_stuff函数与color变量,
就算客户程序员看了shape.c,
他也不可以调用do_stuff与直接访问color成员变量的.
C做到了接口与行为上的高内聚

@C++ 不管你用到什么东西,都必须在头文件声明出来,
哪怕这些东西是prive的(自己用的), 给人一种赤裸裸的感觉.
同样客户程序虽然知道有color成员变量与do_stuff函数
,但是他不可以调用do_stuff与直接变量color;
C++只做到了实现上的高内聚, 头文件会暴露一定细节

@Objelt C 从Object C的代码形式上可以看到,
Object C同样做到了C那样可以从接口与行为上的高内聚,
但是其实这里面有一个缺陷就是,
在上述代码中虽然没有导出接口do_stuff, 但是如果客户程序员知道阅读了源码的话,其实他是可以调用do_stuff这个函数的.
2. 关于函数调用方式

3. 关于命名空间

《C, C++, Object C 初步比较》有1条评论

  1. c是全能手,小巧强大,所向披靡,可靠,任何事情都能对付;
    C++是新的C,双倍能力,双倍尺寸,适应险恶环境,嘿嘿,但是没练好就去驾驶,小心翻车。
    OC啊,不知道会流行多久呢。。
    哈哈哈哈

    回复

发表评论

twenty three − = 17