第0章 序幕
内联函数
内联函数即具有函数的结构,而在编译后却不具备函数的性质。内联函数不是在调用时发生控制转移,而是在编译时将函数体嵌入在每一个调用处。编译时,类似宏定义。
“For function-like macros, prefer inline functions to #defines.”
C++比C的优势
1、c++支持内联,开销更小
2、全局名字更编译管理
用类实现一个Trace,其方法直接叫on,off
而用非类的实现,其方法叫trace_on, trace_off
3、易于扩展,因为C++支持多个构造函数,而面向过程编程,则需要添加新的函数体
C++采用类,将状态和动作绑定在一起,而C则不然。
// c++ code // c code // c++ style c code
s.push(x) push(x); push(x, s);
s.push(y); push(y); push(y, s);
s.add(); add() add(s);
z = s.pop(); z=pop(); z=pop(s);
显而易见,c code当操作其他s时,其需要额外实现类似的函数。
本书坚持以两个思想为核心:实用和抽象
第一篇 动机
C++可以使程序变得很简洁明了
C++有string类,提供功能强大的字符串操作
第二章 为什么用C++工作
抽象
第三章 生活在现实世界中
C++优势在于的它的可移植性和并存性。
第二篇 类和继承
第5章 代理类
目的:使一个C++容器有能力包含类型彼此不同而彼此相关的对象
class VehicelSurrogate {
public:
VechicelSurrogate();
VechicelSurrogate(const Vehicel&);
~VehicelSurrogate();
VehicelSurrogate(const VehicelSurrogate&;
VehicelSurrogate &operate=(const VehicelSurrogate&);
double weight() const;
void start();
// ...
private:
Vehicel* vp;
}
第6-7章 句柄
目的:1、对于需要指向同一块数据的对象,不复制数据对象,而引入引用计数减少内存开销;2、如果有多个指针指向同一个对象,需要进行释放管理,从而引入智能指针(smart point)
class Point {
public:
Point(): xval(0), yval(0){}
Point(int x, int y): xval(x), yval(y) {}
int x() const {return xval;}
int y() const {return yval;}
Point& x(int xv) {
xval = xv; return *this; }
}
Point& y(int yv) {
yval = yv; return *this; }
}
};
class Handle {
public:
Handle():p(new Point()), u(1) {}
Handle(int xv, int yv) : p(new Point(xv, yv)), u(1) {}
Handle(const Point& point) : p(new Point(point)), u(1){}
Handle(const Handle& handle) : p(handle.p), u(handle.u){ ++u; }
Handle& operator=(const Handle& handle) {
if(--u == 0)
delete p;
++handle.u;
p = handle.p;
return *this;
}
~Handle() {
if(--u == 0)
delete p;
}
int x() const {return p->x();}
Handle& x(int xv) {
if(u!=1) {
--u;
p = new Point(*p);
}
p->x(xv);
return *this;
}
int y() const {return p->y();}
Handle& y(int yv) {
{/*类似Handle x*/}
}
private:
Point* p;
int u; // 引用计数
};