【C++】002、const关键字使用

一、概念

  • const关键字在C++中不只是表示常量,他的核心是只读契约

二、const五大常见用法

1、基本常量

  • 用于替代#define

  • 特点:编译器常量,有类型检查,比宏安全

cpp 复制代码
const int SIZE = 20;

2、const与指针

  • 根据const与指针符号*的前后位置,记忆口诀: 左定值,右定向
1)、指向常量的指针
  • const在*左边,定值

  • 特点:值不能改,但指针可以改(是顶层const)

cpp 复制代码
const int* p = &a; 
*p = 10; // 错❌️ 
p = &b; // 对✅️
2)、常量指针
  • const在*右边,定向

  • 特点:指向不能改,但值可以改(是顶层const)

cpp 复制代码
int* const p = &a;
*p = 10; // 对✅️ 
p = &b; // 错❌️
3)、指针常量指针
  • 既不能修改值,也不能修改指向
cpp 复制代码
const int* const p = &a;

3、const引用传参

  • 函数的参数使用const进行修饰

  • 优点:

    • 避免拷贝,传递引用

    • 防止参数被修改,const保护作用

    • 可接受临时变量 printData("hello");

cpp 复制代码
void printData(const std::string& str) { }

4、const成员函数

  • 在成员函数声明末尾加const,表示该函数不会修改任何非静止成员(变量mutable成员除外)

  • 特点:const对象只能调用const成员函数

cpp 复制代码
class Student {
private:
    mutable int cache_hits; // 即使const函数也可以改
    int age;
public:
    // const成员函数内,this被隐式视为 const Student* const this
    int getAge() const { 
        // age = 10; // ❌ 编译报错
        cache_hits++; // ✅ 允许,因为mutable
        return age; 
    }
};

5、const修饰函数返回值

  • 返回引用防止返回值修改
cpp 复制代码
const Student& getStudent() { return stu; } // 返回引用防修改
const int getValue() { return 1; }          // 防止 (a = getValue()) = 3 这样的左值赋值操作

三、指针常量、常量指针与 指针int* 的相互赋值

  • 底层const (const int *),规定指向的值不能改变,赋值给int*后,约束破坏了,他可以修改对象的值

  • 顶层const (int* const), 指向的指针不能改变,但是对象值可以改变,不受影响

四、constexpr与const的区别

  • const是运行时常量,只读契约

  • constexpr是编译器常量。