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

3ca151e8f1fee7709e8facb45ef88cb3.png

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

3b03c4b832c73371d0058d09c184220b.png

3、const 修饰函数体

const 修饰函数体时,放到函数体的行尾处,表明在该函数体内,不能修改对象的数据成员,且不能调用非 const 成员函数。比如:

  • void SetAge(int age)
  • void SetAgeConst(int age) const

两者的区别在于:前者可以修改类的数据成员,而后者不可以。

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

编译的报错信息如下:

2297bd347d17317b28c3c175e43000c5.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值