const


#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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值