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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短