const
程序员文章站
2022-03-16 09:03:25
...
#include<iostream>
using namespace std;
int main()
{
int i = 0;
const int constInt = 1;
//constInt = 2; // 错误:向只读变量‘constInt’赋值
//int &intRef = constInt;//错误:将类型为‘int&’的引用初始化为类型为‘const int’的表达式无效
//int *intPtr = &constInt;//错误:从类型‘const int*’到类型‘int*’的转换无效 [-fpermissive]
/*
double d = 3.123;
int &i = d;//错误:将类型为‘int&’的引用初始化为类型为‘double’的表达式无效
*/
const double constDouble = 3.123;
const int &constIntRef = constDouble;
//上一行代码会被编译器转换为:
const int temp = constDouble;
const int &ri = temp;
cout << "constIntRef:" << constIntRef << endl;
cout << "ri:" << ri << endl;
//从右往左读
const int* constIntPtr;//可以不初始化
constIntPtr = &constInt;//指针,指向的是一个整形的常量
//*constIntPtr = 0;//错误:向只读位置‘* constIntPtr’赋值
//int *const intConstPtr;//错误:未初始化的常量‘intConstPtr’
int *const intConstPtr = &i;//常量,整形指针(指向整形变量的常量指针:这个指针的只能赋值一次,它是一个常量)
//int *const testIntConstPtr = &constInt;//错误:从类型‘const int*’到类型‘int*’的转换无效 [-fpermissive]
//intConstPtr = 0;错误:向只读变量‘intConstPtr’赋值
*intConstPtr = 2;
cout << "*intConstPtr:" << *intConstPtr << endl;
const int* const constIntConstPtr = &constInt;//指向整形常量的常量指针
//int &r = 0;//错误:用类型为‘int’的右值初始化类型为‘int&’的非常量引用无效
const int &r = 0;//那么常量便是有效了
cout << "r:" << r << endl;
int *intPtr = &i;
*intPtr = 3;
//intPtr = constIntPtr;//错误:从类型‘const int*’到类型‘int*’的转换无效
constIntPtr = intPtr;
cout << "*constIntPtr:" << *constIntPtr << endl;
}
constIntRef:3
ri:3
*intConstPtr:2
r:0
*constIntPtr:3
上一篇: linux怎么查看当前登录用户
下一篇: ps怎么上色不超出线稿