C++ - 使用 编译器常量 代替 预处理常量 详解

使用 编译器常量 代替 预处理常量 详解

 

本文地址: http://blog.csdn.net/caroline_wendy/article/details/15809051

对于预处理的单纯常量, 可以使用const类型进行代替;

在面向对象编程中, 类内的常量, 可以使用静态const成员代替,

注意类内(in-class), 静态const成员只允许使用整型常量进行赋值, 如果是其他类型, 是在类内声明, 类外定义的方式;

也可以使用"enum hack", 提供const的作用, 并且给内置(built-in)数组声明;

预处理的函数调用存在很多问题, 可以使用模板内联(template inline)代替, 也可以获得很高的效率;

具体参见代码, 及注释;

代码(/*eclipse cdt ; gcc 4.7.1*/):

/*
 * effectivecpp.cpp
 *
 *  Created on: 2013.11.13
 *      Author: Caroline
 */

/*eclipse cdt ; gcc 4.7.1*/

#include <iostream>
#include <string>
#include <array>

#include <algorithm>

using namespace std;

#define ASPECT_RATIO 1.653 //长宽比

#define CALL_WITH_MAX(a, b) f((a) > (b) ? (a) : (b))

class GamePlayer {
public:
	static const int NumTurns = 5;
	static const double PI ; //不能内类初始化非整型
	enum {eNumTurns = 5}; //枚举类型
	std::array<int, NumTurns> scores;
	std::array<int, eNumTurns> escores;
};
const double GamePlayer::PI = 3.14;

template<typename T>
void f (T a) {
	std::cout << "f : " << a ;
}

template<typename T>
inline void callWithMax(const T& a, const T& b)
{
	f(a>b ? a : b);
}

int main (void) {

	//预处理器定义
	std::cout << "ASPECT_RATIO = " << ASPECT_RATIO << std::endl;

	//常量定义
	const double AspectRatio = 1.653;
	std::cout << "AspectRatio = " << AspectRatio << std::endl;

	//常量指针
	const char* const authorName = "Caroline";
	std::cout << "authorName = " << authorName << std::endl;

	//常量指针
	const std::string sAuthorName("Caroline");
	std::cout << "sAuthorName = " << sAuthorName << std::endl;

	//class专属常量
	GamePlayer gp;
	std::array<int, GamePlayer::NumTurns> scores = { {1, 2, 3, 4, 5} };
	gp.scores = scores;
	std::cout << "gp.scores : ";
	for(const auto s : gp.scores)
		std::cout << s << " ";
	std::cout << std::endl;
	std::cout << "GamePlayer::PI = " << GamePlayer::PI << std::endl;

	//测试宏
	int a = 5, b = 0;
	CALL_WITH_MAX(++a, b); //a, ++两次
	std::cout << " ; a = " << a <<std::endl;
	a = 5, b = 0;
	CALL_WITH_MAX(++a, b+10); //a, ++一次
	std::cout << " ; a = " <<  a <<std::endl;

	//template inline
	a = 5, b = 0;
	callWithMax(++a, b);
	std::cout << " ; a = " << a <<std::endl;

	return 0;

}

 

输出:

ASPECT_RATIO = 1.653
AspectRatio = 1.653
authorName = Caroline
sAuthorName = Caroline
gp.scores : 1 2 3 4 5 
GamePlayer::PI = 3.14
f : 7 ; a = 7
f : 10 ; a = 6
f : 6 ; a = 6


 



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值