标签:
1.用const给字面常量起个名字(标识符),这个标识符就称为标识符常量;因为标识符常量的声明和使用形式很像变量,所以也称常变量
2.定义的一般形式:
(1) const 数据类型 常量名=常量值;
(2)数据类型 const 常量名=常量值;
3.例如:const float PI=3.14159f;
4.注意事项:
(1)常变量在定义时必须初始化;
(2)常变量初始化之后,不允许再被赋值;
代码示例:
//main.cpp #include <iostream> using namespace std;//引入命名空间 int main(void) { //const int a; //1.Error,常量必须初始化 const int a = 100; //a = 200; //2.Error,常量不能重新被赋值 int b = 22; const int * p; //const在*左边,表示*p为常量,经由*p不能更改指针所指向的内容 p = &b; //*p = 200; //2.Error,常量不能重新被赋值 //int * const p2; //1.Error,p2为常量,常量必须初始化 int * const p2 = &b; //const在*右边,表示p2为常量 //int c =100; //p2 = &c; //2.Error,常量不能重新被赋值 *p2 = 200; cout<<b<<endl; cout<<*p<<endl; return 0; }
错误用法编译错误提示信息:
1. constinta;
error C2734: “a”: 如果不是外部的,则必须初始化常量对象
2. constinta = 100; a = 200;
error C3892: “a”: 不能给常量赋值
标签:
原文地址:http://blog.csdn.net/kongshuai19900505/article/details/51588748