找回密码
 立即注册

QQ登录

只需一步,快速开始

工控课堂 首页 工控文库 上位机编程 查看内容

C++中const的强大用法:修饰函数参数/返回值/函数体

2022-4-17 18:03| 发布者: 198366809| 查看: 949| 评论: 0|来自: 算法集市(头条)

摘要: 在C++中,const 常用于修饰常量,告诉编译器某值保持不变。需要注意的是,常量在定义之后就不能修改,因此定义时必须初始化。const int HELLO = 6; // 正确 const int WORLD; // 错误除此之外,const 更强大的地方是 ...
C++中const的强大用法:修饰函数参数/返回值/函数体

在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,使得函数体不能作为左值。

C++中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;
}

编译的报错信息如下:

C++中const的强大用法:修饰函数参数/返回值/函数体


关注公众号,加入500人微信群,下载100G免费资料!

最新评论

热门文章
关闭

站长推荐上一条 /1 下一条

QQ|手机版|免责声明|本站介绍|工控课堂 ( 沪ICP备20008691号-1 )

GMT+8, 2025-12-23 00:43 , Processed in 0.252697 second(s), 23 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

返回顶部