资讯动态

void func() const的使用

发布时间:2026/8/25 4:47:15 来源:尧图企业网站定制
一、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;};

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价