C++面向对象编程总结
一、Object Based(基于对象):面向的是单一class设计
1、class without pointer members. Complex
对于Complex类设计需要注意以下要点
(1). 头文件书写需要加上防卫式声明。
#ifndef __COMPLEX__
#define __COMPLEX__
...
#endif //__COMPLEX__
(2). 构造函数的初始化列表要用起来。(initialization list)
complex (double r = 0, double i = 0): re(r), im(i){ }
(3). 成员函数要不要加const ,该加必须加。
double real () const { return re; }
(4). 参数传递尽量 pass by reference。
(5). 返回值,只要不是 local object 都 returen by reference。反之 return by value。
(6). 相同class的各个object 互为友元。(frends)
(7). 类中所有的非静态成员函数都有一个隐含的参数:this 。 谁调用函数, 谁就是 this。
2、class with pointer members. String
(8). class with pointer members 必须有 copy ctor 和 copy op=.
String(const String& str); //copy ctor 拷贝构造
String& operator=(const String& str); //copy op=. 拷贝赋值
(9). copy op= 必须检测自我赋值 (self assignment)。
inline
String& String::operator=(const String &str)
{
//检测是否 self assignment
if (this == &str)
return *this;
delete [] m_data;
m_data = new char [strlen(str.m_data) + 1];
strcpy(m_data, str.m_data);
return *this;
}
(10). new : 先分配内存, 再调用 ctor
Complex* pc = new Complex(1,2); //这句编译器将转化为以下三步.
void * mem = operator new( sizeof (Complex)); // 1、分配内存
pc = static_cast<Complex*>(mem); // 2、转型
pc->Complex::Complex(1,2); // 3、调用构造函数
(11). delete : 先调用 dtor ,再释放内存
delete pc;// 这句编译器将转化为以下二步.
Complex::~Complex(pc); // 调用析构函数.
operator delete(pc); // 释放内存
(12). 动态分配所得内存
A. malloc 分配内存时, 在内存的最前面和最后面分别有4个字节的内容,说明分配了多少字节。
B. free 时根据这个头尾的标记就知道释放多少内存了。
(13). array new 一定要搭配 array delete,array new时会在对象数组的最前面有4个字节,记录了new 了多少个这样的对象。array delete 时会根据这个数据去调用析构函数。
(14). 关于static。 static的成员变量无论有多少份对象, 内存中它永远只有一份, static 的成员变量必须全局定义。 static的成员函数是没有隐含的this指针参数。
二、Object Oriented (面向对象):类之间的关系
A、Inheritance (继承)
B、Composition (复合)
C、Delegation (委托)
1、Composition(复合),表示 has - a.
构造时:由内而外
析构时:由外而内
经典设计模式:Adapter
2、Delegation(委托),Composition by reference.
经典设计模式:pimpl
3、Inheritance(继承),表示 is - a.
构造时:由内而外
析构时:由外而内
经典的设计模式:
(1)、Template Method,模板方法
将某些操作延迟到子类来实现。
(2)、Observer(观察者模式)
解决一对多依赖关系
(3)、Composite(组合模式)
类图里符号说明:
+:public
-:private
#:protected
_:static
(4)、Prototype(原型模式)