条款一:仔细区别pointers和references
没有所谓的null reference
reference总是指向同一个对象
条款二:最好使用c++转型操作符
static_cast<type>(expression):
不能用来将struct转换成int,double转换成pointer,不能移除表达式的常量性
const_cast<type>(expression):
改变表达式的常量性和变易性(volatileness),编译器的优化
dynamic_cast<type>(expression):
安全的向下转型和跨系转型动作
无法再缺乏虚函数的类型上
#include <iostream>
using namespace std;
class Base_class
{
public:
Base_class(int d=0):data(d)
{
cout<<"base class"<<endl;
}
virtual void test()
{
cout<<"base class"<<endl;
}
private:
int data;
};
class Child_class:public Base_class
{
public:
Child_class()
{
cout<<"Child class"<<endl;
}
virtual void test()
{
cout<<"Child class"<<endl;
}
private:
};
void getinstance(Base_class * b)
{
b->test();
}
void getinstance2(Child_class *c)
{
c->test();
}
int main()
{
Child_class * c = new Child_class();
Base_class *b = c;
getinstance(c);
getinstance2(dynamic_cast<Child_class*>(b));
return 0;
}
reinterpret_cast:与编译平台相关,转换函数指针类型
条款3:绝对不要以多态方式处理数组
多态和指针算术不能混用
array[i] = *(array+i)array和array+i之间的距离为i*sizeof(BST)
条款4:非必要不提供default constructor
对于没有默认构造函数的class,如何定义一个数组:
方法一:
int i1,i2,i3....
EquipmentPiece bestPieces[]={EquipmentPiece(i1),EquipmentPiece(i2),}EquipmentPiece(i3),...
方法二:
typedef EquipmentPiece * PEP;
PEP bestPieces[10];//或者PEP * bestPieces=new PEP[10];
for(int i=0;i<10;i++)
{
bestPieces[i] = new EquipmentPiece (id);
}
方法三:
placement new;
void * rawmemory = operator new[] (10*sizeof(EquipmentPiece));
EquipmentPiece * bestPieces = static_cast<EquipmentPiece*>(rawmemory);
for(int i=0;i<10;i++)
{
new(&bestPieces[i])EquipmentPicece(id);
}
for(int i=9;i>=0;i++)
{
bestPiceces[i].~EquipmentPiece();
}
operator delete[](rawMemory);//本能delete[] bestpieces;
对于templates而言,被实例化的“目标类型”必须有一个default constructor;