首页 > 编程知识 正文

函数后面加const是什么意思,const函数的定义

时间:2023-05-06 02:01:23 阅读:279580 作者:702

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的成员函数。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。