c++ 类成员函数前、后、参数前加const

区别

1、参数前加const:int fun(const int a)

a在函数里不可被修改;

2、函数前加const:const int* const fun( )

函数返回的指针或者是引用,加const规定返回值不可被修改;

3、函数后加const:int fun( ) const

这个函数不能访问类中所有this所能调用的内存,即这是个只读函数;类的成员函数后面加了const关键字,说明这个函数是不能改变类中的成员变量的;如果在编写该ocnst成员函数时,不慎修改了数据成员,或者调用了其他非const成员函数,编译器将指出错误,这就提高了代码健壮;

c++测试代码

#include<iostream>
using namespace std;
#include<string>
class student
{
public:
    void Push(int elem);
    int Getname() const; // const 成员函数
private:
    string name;
    int age;
};
void student:: Push(int elem) {
}

int student::Getname( ) const
{
    //++age; // 编译错误,企图修改数据成员age
    //Push( );// 编译错误,企图调⽤⾮const函数
    return age;
}
int main() {
	
	return 0;
}

注意:

  • 在类中被const声明的成员函数只能访问const成员函数,⽽⾮const函数可以访问任意的成员函数,包括const成员函数;
     

  • 8
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值