1、对于单纯的常量,最好用const对象或者enums来替换#define;
2、对于用来替代define宏的函数,最好用inline该替换掉define,省的一些无所谓的替换问题。
在一个类中,做一个专属于该类的常量,为了将常量的作用域限定在class内,那么就要将其设置为该class的一个成员,同时为了保证该class只有一份实体,那么就要设置为static成员。
那么可以在类中加上声明:
static const int NumTurns=5;
当你需要取得这个NumTurns的地址的时候,如果你不做其他处理,这样是编译出错的,因为编译器一定要看到一个定义式。那么就需要在CPP源文件中进行一个定义:
const int GamePlayer::NumTurns;
那么就能够取到它的地址。
那么无论声明多少个class的变量,该变量都为同一个。
02.h:
#ifndef _02_H_
#define _02_H_
class GamePlayer
{
public:
GamePlayer();
~GamePlayer();
private:
static const int NumTurns = 5;
int scores[NumTurns];
};
#endif
02.cpp:
#include "02.h"
#include <iostream>
using namespace std;
const int GamePlayer::NumTurns;
GamePlayer::GamePlayer()
{
cout << &NumTurns << NumTurns << endl;
}
GamePlayer::~GamePlayer()
{
}