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

2023-02-24 0 292

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

在C++中,const 常用作润色自变量,说C++某值维持维持不变。须要特别注意的是,自变量在表述后就无法修正,因而表述时要调用。

const int HELLO = 6; // 恰当 const int WORLD; // 严重错误

除此以外,const 更强悍的地方性是润色表达式模块、表达式codice、表达式体

被 const 润色的小东西都受强制性为保护,能避免不幸更动,提升流程的易用性。许多C++的书刊提议“use const whenever you need”。

1、const 润色表达式模块

对表达式的入参,无论是甚么正则表达式,也无论是 操作符传达,却是 提及传达,假如加了 const 润色,就能避免表达式内不幸修正该模块,起著为保护促进作用。

比如说上面的范例,给 a 和 b 加之const润色后,假如表达式内的句子企图修正 a 或 b,GUI就会算出严重错误。

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

2、const 润色表达式codice

用 const 润色回到的操作符或提及,为保护操作符或提及的文本不被修正。比如说:

int& GetAge()const int& GetAgeConst()

二者的差别是:前者回到的是两个左值,其提及的文本能被修正;前者回到的是两个左值,其提及的文本不容被修正。

#include <iostream> using namespace std; class Student { public: int& GetAge() { return m_age; } const int& GetAgeConst() { returnm_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; // C++会报错 stu.ShowAge(); return 0; }

编译的报错信息如下,为了安全起见,在表达式的codice加之 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的强大用法:修饰函数参数/返回值/函数体

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务