const用法,指针、引用、函数、成员函数
const和普通变量
常量局部变量
1 2 3
| const int x = 10;
cout << "x = " << x << endl;
|
常量全局变量
与局部时一致
1 2 3 4 5 6
| const int GLOBAL_CONST = 100;
void example() { cout << "GLOBAL_CONST = " << GLOBAL_CONST << endl; }
|
const和引用
1 2 3 4 5 6 7
| int main() { int a = 10; const int &ref = a; ref = 20; return 0; }
|
const和指针
快速记忆,看是type*(可以改本身,不能改指向的值)还是*const(可以改指向的值,不能改本身)
常量指针
- 指针指向的值不能更改
- 指针本身可以修改(改变指向)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> using namespace std;
int main() { const int x = 10; const int *ptr = &x; cout << "*ptr = " << *ptr << endl;
int y = 200; ptr = &y; cout << "*ptr = " << *ptr << endl; return 0; }
|
指针常量
和常量指针相反
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> using namespace std;
int main() { int value = 10; int *const ptr = &value; *ptr = 20; cout << "*ptr = " << *ptr << endl;
int value2 = 30; return 0; }
|
常量指针常量
指针和指向的值都不能更改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include <iostream> using namespace std;
int main() { int value = 10; const int *const ptr = &value;
*ptr = 20; int value2 = 30; ptr = &value2; return 0; }
|
const与函数参数
const常常用来修饰函数的参数,表示该参数不可修改
基本使用
1 2 3 4 5
| void example1(const int x) { x++; cout << "x = " << x << endl; }
|
1 2 3 4 5
| void example2(const int &x) { x++; cout << "x = " << x << endl; }
|
1 2 3 4 5
| void example1(const int *x) { *x = 20; cout << "x = " << *x << endl; }
|
结合指针
参考前面的coanst和指针
1 2 3 4 5 6
| void example1(const int *x) { *x++; cout << "x = " << x << endl; cout << "x = " << *x << endl; }
|
1 2 3 4 5 6
| void example1(const int *x) { ++*x; cout << "x = " << x << endl; cout << "x = " << *x << endl; }
|
1 2 3 4 5 6 7
| void example1(const int *x) { *x++; *x = 100; cout << "x = " << x << endl; cout << "x = " << *x << endl; }
|
1 2 3 4 5 6
| void example1(const int *x) { (*x)++; cout << "x = " << x << endl; cout << "x = " << *x << endl; }
|
1 2 3 4 5 6 7 8
| void example1(const int *const x) { *x++; *x = 100; cout << "x = " << x << endl; cout << "x = " << *x << endl; }
|
修饰成员函数
- const在函数名称后面
- 该成员函数不会修改类中除了被
mutable 修饰的成员
mutable关键字用于修饰类成员变量,使得该变量可以在常量成员函数中修改
myheader.cpp
MyClass中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include <iostream> #include "myheader.h"
MyClass::MyClass(int val) : x(val) {}
void MyClass::display() { std::cout << "x = " << x << std::endl; }
void MyClass::setX(int val) { x = val; }
void MyClass::modX(int val, int val2) const { x = val; y = val2; }
|
修饰函数返回值
- 表示返回的值是常量,不允许修改。这通常用于返回指向常量的指针或引用。
- 参考前面的const和常量,const和指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <iostream> using namespace std;
const int &getConstant() { static int x = 10; return x; }
int main() { const int &ref = getConstant(); ref = 20; return 0; }
|