Google C++编程风格指南(二)

来源:互联网 发布:网络段子视频 编辑:程序博客网 时间:2024/06/05 09:46

1.不具名命名空间

与static起到的效果一样,但是具有外链性,但是因为是不具名命名空间,所以实际上访问不到

代码

1.h

void test1();

1.cc

#include "1.h"#include <stdio.h>int a = 0;void test1(){    printf("%d\n",a);    return;}

2.h

void test2();
2.cc

#include "2.h"#include <stdio.h>//int a = 2;fatal error LNK1169: 找到一个或多个多重定义的符号//static int a = 2; OKnamespace{    int a = 2;//OK}void test2(){    printf("%d\n",a);    return;}

test.cc

#include "1.h"#include "2.h"int main(){    test1();    test2();    return 1;}


2.具名的命名空间

利用命名空间解决符号重名

1.h

//使用命名空间namespace A{class A{public:    A();    ~A();    void test1();};}
1.cpp

#include "1.h"#include <stdio.h>namespace A{A::A(){}A::~A(){}void A::test1(){    printf("test1\n");}}

2.h

//使用命名空间namespace B{class A{public:    A();    ~A();    void test1();};}

2.cpp

#include "2.h"#include <stdio.h>namespace B{    A::A()    {    }    A::~A()    {    }    void A::test1()    {        printf("test1\n");    }}

test.cpp

#include "1.h"#include "2.h"int main(){    A::A a;    B::A b;    a.test1();    b.test1();    return 1;}

//是不是用符号查看器观察一下C++编译过后的(C++扭曲过后)符号比较好?

使用dumpbin.exe查看1.obj
01D 00000000 SECT4  notype ()    External     | ??0A@0@QAE@XZ (public: __thiscall A::A::A(void))
01E 00000000 SECT6  notype ()    External     | ??1A@0@QAE@XZ (public: __thiscall A::A::~A(void))
01F 00000000 SECT8  notype ()    External     | ?test1@A@1@QAEXXZ (public: void __thiscall A::A::test1(void))

2.obj

01D 00000000 SECT4  notype ()    External     | ??0A@B@@QAE@XZ (public: __thiscall B::A::A(void))
01E 00000000 SECT6  notype ()    External     | ??1A@B@@QAE@XZ (public: __thiscall B::A::~A(void))
01F 00000000 SECT8  notype ()    External     | ?test1@A@B@@QAEXXZ (public: void __thiscall B::A::test1(void))

//使用using namespace 可能会导致的一个问题

#include "1.h"#include "2.h"using namespace A;using namespace B;int main(){    //A::A a;    //B::A b;    //A a; error C2872: “A”: 不明确的符号    //A b;    //a.test1();    //b.test1();    return 1;}

使用命名空间别名

//#include "1.h"#include "2.h"//using namespace A;namespace C=B;using namespace C;int main(){    //A::A a;    //B::A b;    //A a; error C2872: “A”: 不明确的符号    //A b;    //a.test1();    //b.test1();    A a;    return 1;}

3.非成员函数,静态成员函数和全局函数

不使用全局函数,考虑使用静态成员函数。

或者说是命名空间的非成员函数(实际上和全局函数性质一样,不过避免了符号问题)

 

4.局部变量

考虑到对象在作用域边界会构造和析构,也可以利用这个特性处理一些事务。

1.cpp

 

#include <iostream>using namespace std;class test{public:test(){cout << "test" << endl;};~test(){cout << "~test" << endl;};void dosth(){cout << "dosth" << endl;};};int main(){test t1;for (int i = 0;i < 5;++i){t1.dosth();}for (int i = 0;i < 5;++i){test t2;t2.dosth();}}


 5.全局变量

全局及静态对象禁止使用,考虑单件模式