Effective C++ 笔记1

条款1:视C++为一个语言联邦编程

一、C、Object-Oriented C++、Template C++ 、STL 组成了C++,高效编程取决你使用C++的哪一部分安全

 

条款2:尽可能用const ,enum,inline替换 #define函数

一、Const 代替 #define中普通的宏,编译器会对类型进行检查避免类型错误。spa

//如这里
#define PI 3.1415
//最好用const代替,一旦定义错了define只会对3.1415进行提示,而不会对PI进行提示,由于在预处理的时候PI已经被3.1415代替了
Const double PI=3.1415

 

二、inline 代替#define中形似函数的宏,赞成能够避免宏定义错误指针

 

//这样定义不安全
#define CALL_WITH_MAX(a,b) f((a)>(b)?(a):(b))
//采用inline
template<typename T>
inline T callWithMax(const T& a,const T& b)
{
    return a>b?a:b;   
}

 

三、类中有const 必需要有static,有const就表示该属性是只有一份因此必须也是静态的code

Class C
{
    static const int pi;    
}

 

四、若是不容许类中static初始化,那么用enum代替对象

//旧的编译器不支持static在声明时得到初值
Class C
{
private:
    static const double PI;
};    
const double C::PI=3.14159;
//因此用这种方式来定义静态变量
Class C
{
privateenum{num=5};
};

 

五、Ifdef/ifndrf 能够防止类被重复引用blog

#ifdef _TEST_
#define _TEST_

int max(int a,int b);

#endif

 

 

条款3:尽可能使用const队列

一、Const出如今星号左边,被指物是常量。右边指针自身是常量编译器

char greeting[]="hello"
//值常数
const char* p=greeting;
//指针常数
char* const p =greeting;
//指针和值都是常数
const char* const p=greeting;

二、Const定义迭代器错误,应该使用const_iteator

std::vector<int> vec;

const std::vector<int>::iterator it=vec.begin();
*it=10;
//错误 迭代器自己是常量
++it;
    

std::vector<int>::const_iterator it=vec.begin()
//错误,该迭代器指向的值是常量
*it=10;
++it;

三、函数返回 const 可避免无心义的赋值动做

 

条款4:肯定对象使用以前已先被初始化

一、  永远在对象使用以前初始化

二、  类中初始化不要用构造函数赋值的形式,要使用成员初值列

class C
{
    int a;
    int b;
    int c;
        //初始化队列 
    C(int x,int y)
        :a(x),
         b(y),
         c(1)
    {
    }
};
相关文章
相关标签/搜索