林锐《高质量C++编程》总结

来源:互联网 发布:长治学院网络教学平台 编辑:程序博客网 时间:2024/06/06 19:54
一、变量的声明格式
1)静态变量用 s_
2)全局用 g_
3)成员变量 m_data

二、断言的使用,assert断言的注释要清晰
在函数的入口处,使用断言检查参数的有效性(合法性)

三、内存指针,注意:内存指针在使用前,一定要做判空处理!!!
1)使用malloc 或是 new 申请内存后,要立即检查指针是否为NULL
2)用free或delete释放内存之后,立即将指针设置为NULL,防止产生野指针
例如: free(p)   p=NULL;

3) 指针在创建的时候,就进行初始化,让它指向NULL,如:char *p = NULL; // 在声明的同时,就初始化。
4) 如果内存分配不成功,直接 exit(1) 关闭程序

四、引用C函数, extern "C" 解决名字匹配问题
extern "C"
{
    void foo(int x, int y);
}
or
extern "C"
{
    #include "myHeader.h"
}

五、多态中,同名函数的不同参数问题,如:
class A
{
    public:
       virtual int a(float f){cout<<"A::a()"<<endl;};
};

class B:public A
{
    public:
       int a(int i){cout<<"B::a()"<<endl;};
};

int main()
{
    B b;
    A *pa = &b;
    B *pb = &b;
    pa->a(3.14f);     //A::a();   注意,这里是调用了父类的方法,不管有无virtual修饰,类型是int或float都将调用父类的方法
    pb->a(3.14f);     //B::a();
    // 同名函数,不同类型参数的话,各调用各自的函数!!!

    return 0;
}

六、内联函数
内联函数减少了一般函数的调用过程的开销,相当于嵌入进程序中,类似于复制进去。提高函数的执行效率。
inline应该与函数定义放在一起,而不是放在函数声明的地方。

class A
{
   public:
      void fun(int x){...};   // 成员函数建议都声明为内联函数
};
inline void A::fun(int x){...};

七、虚析构函数
建议所有的析构函数都为虚函数,这样才能够调用派生类的析构函数。
Base *pb = new Derived;   
delete pb;   // 如果基类的析构函数不是虚函数的话,那么就不会自动调用Derived类的析构函数

八、const const可以修饰常量,函数参数,函数返回值等。
任何不会修改数据成员的函数都应该声明为 const 类型,如果在编写const成员函数时,
不慎修改了数据成员,或是调用其他的非const成员函数,编译器都将指出错误。
简单来说就是:成员函数用const修饰之后,就不能在函数里修改成员变量了。
int GetCount(void) const;   // const 放在了最后面


九、String类的构造,析构,拷贝,赋值函数

#include <iostream>#include <cstring>using namespace std;class String{    public:        String();        ~String();        String(const char *str);                       // 普通构造函数        String(const String &other);                   // 拷贝函数        String &operator=(const String &other);        // 赋值函数    private:        char *m_data;};String::String(const char *str){    if (str==NULL)    {        m_data = new char[1];        *m_data='\0';    }    else    {        int length = strlen(str);        m_data = new char[length+1];        strcpy(m_data,str);    }}String::~String(){    delete []m_data;   // 释放内存空间}String::String(const String &other){    // 因为引用不可能为空,所以这里不需要判空    int length = strlen(other.m_data);    m_data = new char[length+1];    strcpy(m_data, other.m_data);}String & String::operator=(const String &other){    // 检查是否是同一对象    if (this==&other)    {        return *this;    }    // 释放掉原先的资源    delete []m_data;    // 重新分配空间,并赋值    int length = strlen(other.m_data);    m_data = new char[length+1];    strcpy(m_data, other.m_data);    // 返回本对象的引用    return *this;}int main(){    return 0;}


十、本书作者的建议:
如果有必要的话,可以使用 PC_Lint, LogiScope 等工具进行代码审查

对个人来说,经常检查你的代码并且自问“我怎样才能写得更好呢?” 这会加速你的成长,让你成为一个更优秀的程序员。



1 0
原创粉丝点击