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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短