[转]函数声明后面的const用法
通常我们会看到一些函数声明后面会跟着一个const,如下
void function() const{}
这个const是做什么的呢?
看一下下面的例子,就知道了。直接在编译前,就会提示下面的两个错误.
#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 main(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 IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步