const是C++中用于定义常量、限制修改权限的关键字,它的使用场景非常广泛,不同场景下的语法规则和作用都有区别,下面我们逐一讲解。

const修饰普通变量
这是const最基础的用法,用来定义值不可修改的常量,定义时必须初始化,之后任何尝试修改该变量的操作都会编译报错。
#include <iostream>
using namespace std;
int main() {
const int MAX_NUM = 100; // 定义常量MAX_NUM,必须初始化
// MAX_NUM = 200; // 错误,const修饰的变量不能被修改
cout << MAX_NUM << endl; // 输出100
return 0;
}
const修饰指针
const修饰指针时有两种常见情况,分别对应不同的限制规则,需要区分清楚。
指向常量的指针(常量指针)
语法为const 类型* 指针名,表示指针指向的内容是常量,不能通过指针修改指向的值,但指针本身可以指向其他地址。
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
const int* p = &a; // 指向常量的指针
// *p = 30; // 错误,不能通过p修改指向的值
p = &b; // 正确,p可以指向其他地址
cout << *p << endl; // 输出20
return 0;
}
指针常量
语法为类型* const 指针名,表示指针本身是常量,指针的指向不能修改,但可以通过指针修改指向地址的值(如果指向的内容不是常量)。
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int* const p = &a; // 指针常量
*p = 30; // 正确,可以修改指向的值
// p = &b; // 错误,指针的指向不能修改
cout << a << endl; // 输出30
return 0;
}
const修饰引用
const修饰引用后得到常量引用,常量引用不能修改其绑定的对象的值,通常用于函数参数传递,避免拷贝的同时防止修改实参。
#include <iostream>
#include <string>
using namespace std;
// 常量引用作为参数,避免拷贝且不会修改实参
void printName(const string& name) {
// name = "test"; // 错误,不能修改常量引用绑定的值
cout << name << endl;
}
int main() {
string s = "张三";
printName(s); // 输出张三
return 0;
}
const修饰函数参数和返回值
函数参数使用const修饰,可以明确该参数在函数内部不会被修改,提升代码可读性,也能避免误操作。如果返回值是指针或引用,用const修饰可以限制接收方修改返回的内容。
#include <iostream>
using namespace std;
// 参数a是const修饰的int引用,函数内不会修改a的值
int add(const int& a, int b) {
// a = a + 1; // 错误,不能修改const参数
return a + b;
}
// 返回指向常量的指针,调用方不能通过返回的指针修改内容
const int* getMax(const int* a, const int* b) {
if (*a > *b) {
return a;
}
return b;
}
int main() {
int x = 5, y = 8;
cout << add(x, 3) << endl; // 输出8
const int* res = getMax(&x, &y);
// *res = 10; // 错误,不能修改指向的常量值
cout << *res << endl; // 输出8
return 0;
}
const与函数重载
类的成员函数中,有没有const修饰可以作为函数重载的依据,const对象只能调用const成员函数,非const对象优先调用非const成员函数。
#include <iostream>
using namespace std;
class Test {
public:
// 非const版本的成员函数
void show() {
cout << "调用非const成员函数" << endl;
}
// const版本的成员函数,构成重载
void show() const {
cout << "调用const成员函数" << endl;
}
};
int main() {
Test t1;
const Test t2;
t1.show(); // 输出:调用非const成员函数
t2.show(); // 输出:调用const成员函数
return 0;
}
const的核心作用总结
- 明确变量的不可修改属性,让代码意图更清晰,减少误操作导致的bug。
- 帮助编译器做优化,比如将const变量存入只读内存区域,提升运行效率。
- 保护函数参数和返回值,避免函数内部意外修改传入的实参,或者防止外部修改返回的敏感内容。
- 支持函数重载,为const对象和非const对象提供不同的处理逻辑。