const

 

const declaration//常量声明
member-function const//修饰类成员函数
When modifying a data declaration, the const keyword specifies that the object or variable is not modifiable. When following a member function's parameter list, the const keyword specifies that the function doesn't modify the object for which it is invoked.
就是说,const仅保证被修饰的成员函数所在的类的成员变量不被修改,其它变量(如该函数的参数和该函数中声明的变量都在保护范围之外)

试验代码:
#include <iostream>

using namespace std;

class Plural
{
public:
void show(int * a_Operand, int a_InTest) const;

 

private:
int m_RealNum;
};

void Plural::show(int * a_Operand, int a_InTest) const//
测试const与函数的搭配用法

{
int i = 0;

cout << i << endl;
cout << *a_Operand << endl;

a_InTest = 6;
a_Operand = &i;
//m_RealNum = 3.0;
i = 2;    

cout << i << endl;
cout << *a_Operand << endl;
cout << a_InTest << endl;
}
int main(void)
{
Plural newOne;
int test = 12;
newOne.show(&test, test);
return 0;
}
此时运行正常,当去掉show成员函数中的注释符“//”时就报错了。

每个类的成员函数(除了静态函数外)都回带有一个指向本身对象的this指针作为自己的第一个形参,是隐形的,例如类 class Exam{
                                                  int m_i;int m_p;
                                                 void set(int i,int j){ m_i = i;m_p = j;}
                                        }
其成员函数set表面上看有两个int类型的参数,实际上还带有一个指向调用对象的this指针,即 该函数应该是

void set (Exam* this,int i,int j){ this.m_i = i;this.m_p = j;}

若为常成员函数,即 函数变为void set(Exam *this,int i,int j)const; const修饰的函数的第一个参数,即修饰指向本身对象的指针,变为const Exam* this;从而this指针变为指向常量的指针,这样的话 在常成员函数中去修改类的数据成员的话,就变成的试图去修改常量,当然是错误的。而函数中声明的其他变量由于没有受到const修饰,是可以更改的。

 

const

1)可以定义const 常量

2const 可以修饰函数的参数、返回值,甚至函数的定义体。被const 修饰的东

西都受到强制保护,可以预防意外的变动,能提高程序的健壮性。

Const int * 表示指针所指向的内存中的值不能变

Int *const  表示指针不能再指向其它内存

Const* int 没有这种用法

Int const * const int * 是一样的。

定义函数返回值类型为const,表示 返回值不能作为左值使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值