通常我们会看到一些函数声明后面会跟着一个const,如下

; ;<pre>void ;function() ;const{}</pre> ; ; ; ;

这个const是做什么的呢?

看一下下面的例子,就知道了。直接在编译前,就会提示下面的两个错误.

; ; ; ;<pre>#include ;&quot;stdafx.h&quot;

#include ;&lt;iostream&gt;

using ;namespace ;std;

class ;aa{

; ; ; ;int ;num;

public:

; ; ; ;aa(){

; ; ; ; ; ; ; ;int ;b ;=10;

; ; ; ; ; ; ; ;num ;= ;b;

; ; ; ;};

; ; ; ;void ;out1(){

; ; ; ; ; ; ; ;cout&lt;&lt;num&lt;&lt;endl;

; ; ; ;}

; ; ; ;void ;out2() ;const{

; ; ; ; ; ; ; ;cout&lt;&lt;num&lt;&lt;endl;

; ; ; ;}

; ; ; ;void ;out3() ;const{

; ; ; ; ; ; ; ;num+=10; ;//出错,const函数不能修改其数据成员

; ; ; ; ; ; ; ;cout&lt;&lt;num&lt;&lt;endl;

; ; ; ;}

};

int ;main(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;

}</pre> ; ; ; ; ; ; ; ;

在类成员函数的声明和定义中,

const的函数不能对其数据成员进行修改操作。

const的对象,不能引用非const的成员函数。

转载于:http://www.cnblogs.com/xing901022/p/3413019.html