C ++中的const成员函数

const成员函数是在程序中声明为常量的函数。这些函数调用的对象无法修改。建议使用const关键字,以避免对对象的意外更改。

const成员函数可以由任何类型的对象调用。非常量函数只能由非常量对象调用。

这是C ++语言中const成员函数的语法,

datatype function_name const();

这是C ++中const成员函数的示例,

示例

#include<iostream>
using namespace std;
class Demo {
   int val;
   public:
   Demo(int x = 0) {
      val = x;
   }
   int getValue() const {
      return val;
   }
};
int main() {
   const Demo d(28);
   Demo d1(8);
   cout << "The value using object d : " << d.getValue();
   cout << "\nThe value using object d1 : " << d1.getValue();
   return 0;
}

输出结果

The value using object d : 28
The value using object d1 : 8