读书笔记: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博客 ” ,链接:http://blog.itpub.net/409557/viewspace-891728/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/409557/viewspace-891728/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值