【嵌入式面经专题】5-深入了解 const

发布时间 2023-07-24 21:51:03作者: FBshark

在C++中,const 常用于修饰常量,告诉编译器某值保持不变。需要注意的是,常量在定义之后就不能修改,因此定义时必须初始化。

const int HELLO = 6;  // 正确
const int WORLD;  // 错误

除此之外,const 更强大的地方是修饰函数参数、函数返回值、函数体。

被 const 修饰的东西都受到强制保护,可以防止意外改动,提高程序的健壮性。很多C++的书籍建议“use const whenever you need”。

 

1. const修饰函数参数时,函数形参在函数体内就变为常量,所指向的内容不可改变;函数参数基本类型的值、指针指向的值、引用变量的值不可改变

比如下面的例子,给 a 和 b 加上const修饰后,如果函数内的语句试图修改 a 或 b,编辑器就会报出错误。

void function(int* output, const classA& a, const classB* b) {
    // do something
}

 

2. const修饰函数返回值时,函数返回值变为常量,所指向的内容不可改变;此时函数返回的基本类型值、指针指向值、引用的变量的值不可改变;其也常用于运算符的重载;

#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;
}

 

 

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、const修饰函数参数时,形参变为常量

2、const修饰函数返回值时,返回值变为不可更改的左值

3、const修饰函数时,不可更改类的成员变量的值