函数声明后面的const用法
void function() const{}
通常我们会看到一些函数声明后面会跟着一个const,这个const是做什么的呢?
看一下下面的例子,就知道了。直接在编译前,就会提示下面的两个错误
// test1107.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> using namespace std; class aa{ int num; public: aa(){ int b =10; num = b; }; void out1(){ cout<<num<<endl; } void out2() const{ cout<<num<<endl; } void out3() const{ num+=10; //出错,const函数不能修改其数据成员 cout<<num<<endl; } }; int _tmain(int argc, _TCHAR* argv[]) { aa a1; a1.out1(); a1.out2(); a1.out3(); const aa a2; a2.out1(); // 错误,const的成员 不能访问非const的函数 a2.out2(); a2.out3(); return 0; }
在类成员函数的声明和定义中,
const的函数不能对其数据成员进行修改操作。
const的对象,不能引用非const的成员函数。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步