区别
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成员函数;