六、const关键字
1、常成员函数
●语法:
class A
{
void ReadA() const //常成员函数
{ //不能出现修改成员属性操场
};
●常成员函数内部不允许修改成员属性
●原理:this原本是一个指针常量. obj * const this; 再函数之后加一-个const.则this会被修饰
变成:const obj * const this this的指向已经指向空间中的内容都不能被修改.
#include <iostream>
using namespace std;
class Num
{
public:
Num():_n1(1),_n2(2)
{
}
void VisitNum() const //常成员函数
{
//不能出现修改成员属性操作
//_n1 = 2; //this->_n1 = 2; const Num * const this;
cout<<_n1<<endl;
cout<<_n2<<endl;
}
int _n1;
int _n2;
};
void test01()
{
Num n1;
n1.VisitNum();
}
int main(int argc, char *argv[])
{
test01();
return 0;
}
2、常对象
●语法:在实例化对象时加const修饰: const Hero h1;
●常对象中的所有属性都不能再被修改. 所以常对象只能调用常成员函数
#include <iostream>
using namespace std;
class Num
{
public:
Num():_n1(1),_n2(2)
{
}
void VisitNum() const //常成员函数
{
//不能出现修改成员属性操作
//_n1 = 2; //this->_n1 = 2; const Num * const this;
cout<<_n1<<endl;
cout<<_n2<<endl;
}
void NumAdd(int a_n)
{
_n1 +=a_n;
_n2 +=a_n;
}
int _n1;
int _n2;
};
void test01()
{
Num n1;
n1.VisitNum();
const Num n2; //常对象中的所有属性都不能再被修改. 所以常对象只能调用常成员函数
//n2.NumAdd(5);
n2.VisitNum();
}
int main(int argc, char *argv[])
{
test01();
return 0;
}