拓冰建站拓冰建站
首页 / 资讯中心 / 正文

void func() const的使用

一、void func() const的使用1.什么是const成员函数2.const成员函数的语法糖3.const成员函数承诺不修改对象状态4.对成员变量的限制5.和const对象的关系6.基于const重载7.mutable关键字8.get函数常用const修饰const 成员函数是 C 中用于保证成员函数不会修改对象内部状态的一种语法机制。它在函数声明或定义的参数列表之后、函数体之前添加 const 关键字。二、void func() const的语法糖class MyClass {public:// 声明int getValue() const;// 定义类内实现int getOther() const {return other_;}private:int value_;int other_;};// 类外定义int MyClass::getValue() const {return value_;}三、承诺不修改对象状态class Counter {public:int getCount() const {// count_ 5; // 错误不能修改成员变量// increment(); // 错误不能调用非 const 成员函数return count_;}void increment() {count_;}private:int count_ 0;};
分享:

看完干货,该让你的企业上线了

免费需求沟通 · 48 小时内出具建站方案 · 河南本地可上门