在C++中,const 常用于修饰常量,告诉编译器某值保持不变。需要注意的是,常量在定义之后就不能修改,因此定义时必须初始化。
const int HELLO = 6; // 正确
const int WORLD; // 错误除此之外,const 更强大的地方是修饰函数参数、函数返回值、函数体。
被 const 修饰的东西都受到强制保护,可以防止意外改动,提高程序的健壮性。很多C++的书籍建议“use const whenever you need”。
1、const 修饰函数参数
对于函数的入参,不管是什么数据类型,也不管是 指针传递,还是 引用传递,只要加了 const 修饰,就可以防止函数内意外修改该参数,起到保护作用。
比如下面的例子,给 a 和 b 加上const修饰后,如果函数内的语句试图修改 a 或 b,编辑器就会报出错误。
void function(int* output, const classA& a, const classB* b) {
// do something
}2、const 修饰函数返回值
用 const 修饰返回的指针或引用,保护指针或引用的内容不被修改。比如:
- int& GetAge()
- const int& GetAgeConst()
两者的区别在于:前者返回的是一个左值,其引用的内容可以被修改;后者返回的是一个右值,其引用的内容不可被修改。
#include <iostream>
using namespace std;
class Student {
public:
int& GetAge() {
return m_age;
}
const int& GetAgeConst() {
return m_age;
}
void ShowAge() {
cout << "Age: " << m_age << endl;
}
private:
int m_age = 0;
};
int main()
{
Student stu;
stu.ShowAge();
stu.GetAge() = 5; // 会修改成员变量的值
stu.ShowAge();
stu.GetAgeConst() = 8; // 编译器会报错
stu.ShowAge();
return 0;
}编译的报错信息如下,为了安全起见,在函数的返回值加上 const,使得函数体不能作为左值。
3、const 修饰函数体
const 修饰函数体时,放到函数体的行尾处,表明在该函数体内,不能修改对象的数据成员,且不能调用非 const 成员函数。比如:
- void SetAge(int age)
- void SetAgeConst(int age) const
两者的区别在于:前者可以修改类的数据成员,而后者不可以。
#include <iostream>
using namespace std;
class Student {
public:
void SetAge(int age) {
m_age = age;
}
void SetAgeConst(int age) const {
m_age = age;
}
void ShowAge() {
cout << "Age: " << m_age << endl;
}
private:
int m_age = 0;
};
int main()
{
Student stu;
stu.ShowAge();
stu.SetAge(6); // 正确
stu.ShowAge();
stu.SetAgeConst(8); // 错误
stu.ShowAge();
return 0;
}编译的报错信息如下:


/1 
