effective c++ 条款2
条款2
- 常量(const)替换宏(#define)
- 指针常量
- 类成员常量
- 枚举(enum)替换宏(#define)
- 模板函数(template inline)替换宏函数
尽量用const,enum,inline替换#define
总结就是:
常量(const)替换宏(#define)
// uppercase names are usually for macros
#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653;
指针常量
双const:指针不能变(只能指向这一块内存空间),指向的内存单元的值也不能变。
std::cout << "测试常量指针" << std::endl;const char* const authorName1 = "StevePro Studios"; //c类型字符串 char* std::cout << *(authorName1 + 0) << *(authorName1 + 1) << std::endl;char* const authorName12 = "StevePro Studios2";authorName12[2] = 'x'; //指针只能指向S的地址(值可变) authorName12[2] =nullptr;不可修改const char* authorName13 = "StevePro Studios3";authorName13 = nullptr; //指针可以指向其他内存空间,但内存空间中的值不能变。 authorName13[2] = 'x';不可修改
或者可以使用string常量代替:
std::cout << "string常量" << std::endl;const std::string authorName2("StevePro Studios"); //c类型字符串 string
类成员常量
- 类的静态成员
- 在头文件声明,在cpp文件中定义
这样也就完成了常量的定义。
std::cout << GamePlayer1::NumTurns << std::endl;GamePlayer2 g2;std::cout << g2.scores << std::endl;
可以在其他函数中,直接调用常量GamePlayer1::NumTurns。
枚举(enum)替换宏(#define)
也可以在其他函数中直接使用常量:
GamePlayer2 g3;std::cout << g3.NumTurns << std::endl;
模板函数(template inline)替换宏函数
#include <iostream>#include "GamePlayer1.h"
#include "GamePlayer2.h"
// uppercase names are usually for macros
#define ASPECT_RATIO 1.653
const double AspectRatio = 1.653;int f(int parm) {std::cout << parm << std::endl;return parm;
}#define CALL_WITH_MAX(a,b) f((a)>(b)?(a):(b))// We don't know what T is so pass by reference-to-const Item20
template<typename T>
inline void callWithMax(const T& a, const T& b)
{f(a > b ? a : b);
}int main()
{std::cout << "测试常量指针" << std::endl;const char* const authorName1 = "StevePro Studios"; //c类型字符串 char* //std::cout << *(authorName1 + 0) << *(authorName1 + 1) << std::endl;//char* const authorName12 = "StevePro Studios2";//authorName12[2] = 'x'; //指针只能指向S的地址(值可变) authorName12[2] =nullptr;不可修改//const char* authorName13 = "StevePro Studios3";//authorName13 = nullptr; //指针可以指向其他内存空间,但内存空间中的值不能变。 authorName13[2] = 'x';不可修改std::cout << "string常量" << std::endl;const std::string authorName2("StevePro Studios"); //c类型字符串 stringstd::cout << "测类中的静态常量" << std::endl;std::cout << GamePlayer1::NumTurns << std::endl;GamePlayer2 g2;std::cout << g2.scores << std::endl;std::cout << "测类中的枚举" << std::endl;GamePlayer2 g3;std::cout << g3.NumTurns << std::endl;std::cout << "测试#define CALL_WITH_MAX(a,b) f((a)>(b)?(a):(b))" << std::endl;int a = 5; int b = 2;CALL_WITH_MAX(++a, b); std::cout << "a的值最后为: " << a << std::endl;a = 5; b = 2;CALL_WITH_MAX(++a, b + 10); std::cout << "a的值最后为: " << a << std::endl;std::cout << "使用模板后" << std::endl;a = 5; b = 2;callWithMax(++a, b);a = 5; b = 2;callWithMax(a, b+10);return 0;
}
宏函数存在的问题
解决办法: