天天看點

effective c++ 盡量以const enum inline 替換 #define

為了将常量的作用域限制在class内,你必須讓它成為class的一個成員

#include <iostream>
#include<cstdio>
#include<cstring>
#include<effective_c.h>
using namespace std;
class A
{
public:
    A();
    const static int NUM = ;//聲明而非定義
    int arr[NUM];
    static const double a = ;
    enum{NUM1 = };
    //代替define的另一種方法
    int arr1[NUM1];
};
extern int x;
A::A(){}
const int A::NUM;
//定義式,因為NUM在聲明的時候已經獲得初始值,定義時不可以再設初值了
#define MAXM 100
int main()
{
    A a;
    const int * c = &a.NUM;
    //為取得a.NUM的位址,需要将NUM定義出來
    cout << x << endl;
}
int x = MAXM;
#undef MAXN 100
//define 的MAXM 被取消

           

const 的位址是合法的

enum的位址通常是不合法的

定義和聲明的講解

定義和聲明的講解2

#include <iostream>
#include<cstdio>
#include<cstring>
#include<effective_c.h>
using namespace std;
#define CALL_WITH_MAX(a,b) ((a) > (b) ? (a) : (b))
template<typename T>
inline T MAX(const T &a,const T &b)
{
    return a > b ? a : b;
}
//獲得和宏同樣的效率
int main()
{
    int a = ,b = ;
    CALL_WITH_MAX(++a,b);
    //a被累加了兩次
    CALL_WITH_MAX(++a,b + );
    //a被累加了一次
}


           

繼續閱讀