ITPub博客

首页 > 应用开发 > IT综合 > 读书笔记:0章序幕

读书笔记:0章序幕

原创 IT综合 作者:karlyang88 时间:2007-01-19 18:12:45 0 删除 编辑
C++沉思录第0章读书笔记[@more@]

第0章:序幕

问题:你能说服我去学习C++,而不是C吗?怎么向没有用过C的人解释C++呢?

0.1第一次尝试

C++核心概念是类。

#include

class Trace {

public:

void print(char *s) { printf("%s", s); }

};

int main()

{

Trace t;

t.print("begin main() n");

t.print("end main() n");

}

0.11改进

#include

class Trace {

public:

Trace() { noisy = 0;}

void print(char *s) { if(noisy) printf("%s", s); }

void on() {noisy = 1;}

void off() {noisy = 0; }

private:

int noisy;

}

0.12进一步改进

如果用户想要修改这样的类,将会如何?“你能让它随时关闭吗?”;“你能让它打印到标准输出设备以外的东西上吗?”。

#include

/*

class Trace {

public:

Trace() { noisy = 0; f =stdout; }

Trace(FILE * ff) { noisy = 0; f= ff;}

void print(char *s)

{ if(noisy) fprintf(f, "%s", s); }

void on() { noisy = 1;}

void off(){noisy = 0; }

private:

int noisy;

FILE*f;

};

int main()

{

Trace t(stderr);

t.on();

t.print("begin main() n");

t.print("end main() n");

}

0.2 不用类来实现

典型的C解决方案会怎样的?

#include

void trace(char *s)

{

printf("%sn", s);

}

// 或者

#include

static int noisy = 1;

void trace(char *s)

{

if(noisy)

printf("%sn", s);

}

void trace_on { noisy = 1; }

void trace_off {noisy = 0;}

与C++比较三个缺点?

1. Trace不是内联的。

2. C版本引入了3个全局名字,C++只一个。

3. 很难将这个例子一般化。

int main()

{

trace("begin main()n");

//main 函数主体

trace("end main()n");

}

0.4一个更大的例子

划分屏幕同时显示两个无关的表单。

0.5结论

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/409557/viewspace-891728/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    35
  • 访问量
    336364