c++ 中定义常量的两种方法
c++中定义常量有两种方法:
1.使用#define预处理器
#define SCREEN_HEIGHT 640
2.使用const关键字
const int SCREEN_WIDTH 960;
所谓常量,即在程序执行期间不会改变的变量,常量可以是任意类型的变量,只不过在定义之后值不可修改,下面测试一下常量在程序中的应用。
正常情况:
#include <iostream>
using namespace std;
#define MY_TEST 10
int main(){
const int HEIGHT = 10;
cout <<"testConst====="<< HEIGHT<<"\n";
cout <<"testDefine====="<< MY_TEST<<"\n";
return 0;
}
测试结果:
testConst=====10
testDefine=====10
异常情况:
#include <iostream>
using namespace std;
#define MY_TEST 10
int main(){
const int HEIGHT = 10;
MY_TEST = 20;
cout <<"testConst====="<< HEIGHT<<"\n";
cout <<"testDefine====="<< MY_TEST<<"\n";
return 0;
}
测试结果:
test.cpp:6:13: error: expression is not assignable(表达式不匹配)
MY_TEST = 20;
~~~~~~~ ^
1 error generated.
看被标注为红色的代码,试图改变常量的值,编译时直接报错,const定义的常量情况也是一样会报错,
测试代码:
#include <iostream>
using namespace std;
#define MY_TEST 10
int main(){
const int HEIGHT = 10;
// MY_TEST = 20;
HEIGHT = 22;
cout <<"testConst====="<< HEIGHT<<"\n";
cout <<"testDefine====="<< MY_TEST<<"\n";
return 0;
}
测试结果:
test.cpp:5:15: note: variable 'HEIGHT' declared const here(HEIGHT被标记为const类型)
const int HEIGHT = 10;
~~~~~~~~~~^~~~~~~~~~~
2 errors generated.
更多推荐



所有评论(0)