const与指针
int age =1;
int *P =&age;
int age =10;
cosnt int *P1 = &age;
int const*P2 = &age;
int *const P3 = &age;
const int *const P4 = &age;
int const *const P5 = &age;
const 与结构体、类
- const修饰结构体、指针,其成员也不可以更改。(修饰存储空间)
const与引用
int age =10;
const int &ref = age;
int & const 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]
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之间的赋值