const

const与指针

  • 指针
int age =1;
int *P =&age;
/*
指针:	指针的地址&p
		指针指向的内容*p、age
变量:	变量的地址&age,p
		变量:age,*p
*/
  • const修饰右边的东西
int age =10;
//p1、p2(指针)不是常量;*p4、*p5(指针指向的内容)是常量
cosnt int *P1 = &age;
int const*P2 = &age;
//p3(指针)是常量;*p3(指针指向的内容)不是常量
int *const P3 = &age;
//p4、p5(指针)是常量;*p4、*p5(指针指向的内容)是常量
const int *const P4 = &age;
int const *const P5 = &age;

const 与结构体、类

  • const修饰结构体、指针,其成员也不可以更改。(修饰存储空间)

const与引用

int age =10;
//类比指针。指向的内容不能修改
const int &ref = age; //等价 int const &ref = age;
//指向不能修改
int & const ref =age; //等价 int & ref = age;

const引用(const在&符号左边)

  • 可以指向临时数据(常量、表达式、函数返回值)
  • 作为函数参数时(此规则也适用const指针)
     可以接受const实参和非const实参
     与非const引用构成重载
#include <iostream>
using namespace std;

int sum(const int& a, const int& b) {
	cout << "sum(const int& a, const int& b)" << endl;
	return 1;
}
int sum(int& a,int& b) {
	cout << "sum(int& a,int& b)" << endl;
	return 1;
}

int main()
{	
//指向不同类型的数据
	const double& ref = sum(1, 3);
	int a = 10, b = 1;
//构成重载
	sum(a, b);
	return 0;
}
  • 可以指向不同类型的数据
     当常引用指向了不同的数据时,会产生临时变量
	int age = 10;
00A41010  mov         dword ptr [ebp-0Ch],0Ah  
	const long& ref = age;
00A41017  mov         eax,dword ptr [ebp-0Ch] 
//[ebp-8]临时变量的地址
00A4101A  mov         dword ptr [ebp-8],eax  
00A4101D  lea         ecx,[ebp-8]  
//引用存的是临时变量的地址值
00A41020  mov         dword ptr [ebp-10h],ecx 

注意

  • const修饰右边的东西
     cosnt int *P1 = &age; 等价int const*P2 = &age;
     int *const P3 = &age;
  • 判断一个变量是什么从右往左看,小括号优先
     int *p[3]
     int (*p)[3]
  • 顶层const和底层const之间的赋值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值