高效的c++ 01减少使用#define
01减少使用#define
开始新的旅程吧!
一、传统枚举
先看看之前的代码:
#define TY_UP 0
#define TY_DOWN 1
#define TY_LEFT 2
#define TY_RIGHT 3
#define TY_IN 4
#define TY_OUT 5
#define TY_LEFT_UP 6
#define TY_RIGHT_UP 7
#define TY_LEFT_DOWN 8
#define TY_RIGHT_DOWN 9
如上所写,代码繁琐,而且编译若报错,就比如TY_IN 报错的是4,而不是TY_IN,不方便调试。
//01.枚举类型的定义
enum YunTaiControlEnum
{
up=1,downn,nleft,nright
};
void main()
{
YunTaiControlEnum m = nright;
//02.对于枚举,只定义了赋值运算符,没有为枚举定义算术运算。
int a = 2;
switch (a)
{
case up:
cout << "up" << endl;
break;
case downn:
cout << "downn" << endl;
break;
case nleft:
cout << "left" << endl;
break;
case nright:
cout << "right" << endl;
break;
default:
break;
}
//03.整数类型转化为枚举类型
int x = 1;
YunTaiControlEnum temp = YunTaiControlEnum(x);
switch (temp)
{
case up:
cout << "up" << endl;
break;
case downn:
cout << "downn" << endl;
break;
case nleft:
cout << "left" << endl;
break;
case nright:
cout << "right" << endl;
break;
default:
break;
}
//04.对于枚举,只定义了赋值运算符,没有为枚举定义算术运算。
temp++;//报错
YunTaiControlEnum tempx = temp + 1;//报错
system("pause");
}
二、强枚举
强类型枚举(Strongly-typed enums),号称枚举类型,是C++11中的新语法,用以解决传统C++枚举类型存在的缺陷。传统C++中枚举常量被暴漏在外层作用域中,这样若是同一作用域下有两个不同的枚举类型,但含有相同的枚举常量也是不可的,比如:
enum Side{Right,Left};
enum Thing{Wrong,Right};
这是不能一起用的。
//01.强枚举类型的定义,如果不加class则会报错,nleft重新定义
enum class YunTaiControlEnum
{
up=1,downn,nleft,nright
};
enum class side{
nleft,nright
};
以下是代码片段:
int a = 3;
switch (YunTaiControlEnum(a))
{
case YunTaiControlEnum::up:
cout << "up" << endl;
break;
case YunTaiControlEnum::downn:
cout << "downn" << endl;
break;
case YunTaiControlEnum::nleft:
cout << "left" << endl;
break;
case YunTaiControlEnum::nright:
cout << "right" << endl;
break;
default:
break;
}
三、用const 替换#define 的时候有两个地方值得注意:
1.定义常量指针-建议使用两个const
Const char *const ptr = “hello world”;
其实更推介const string mystr(“hello world”);
2.类class专属常量,如果要保证只有一个实体则需加static
class test
{
public:
static const int a = 12;//常量声明
int score[a];
}
不要高兴的太早,这只是声明,不是定义,如果是整数类型,且static,const修饰,如果不取地址则无需定义,如果要取地址则必须定义。例如:
const int test::a;//不需要初始值
完整代码如下:
class test
{
public:
test() = default;
static const int a = 10;
int score1[a];
enum MYnUM
{
TyNum = 10
};
int score2[TyNum];
};
enum class side{
nleft,nright
};
const int test::a;
void main()
{
test t;
cout << &t << endl;
cout << t.a << endl;
cout << &t.a << endl;
system("pause");
}