[2]effective c++学习:条款2-尽量以const,enum,inline替换#define

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()
{
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值