以const 修饰的常量值,具有不可变性。
C++的编译器通常不为普通const常量分配存储空间,而是将它们保存在符号表中,这使得它成为一个编译期间的常量。
const 用于指针的两种情况分析:
int const *a; //a/可变,*a不可变
int *const a; //a不可变,*a可变
比如:
typedef char* pStr;
char string[4] = "abc";
//限定*p1不可变,当然p1可变。
const char* p1 = string;
const pStr p2 = string;
p1++; //可行 输出bc
p2++; //不可行
const int nValue; //nValue 是const
const char* pContent; //*pContent是const, pContent可变
char* const pContent; //pContent是const, *pContent可变
const char* const pContent; //pContent和*pContent都是const
#include <iostream>
#include <string>
using namespace std;
string test[] ={"test"};
class StringStack
{
static const int size =100;
const string* stack[size];
int index;
public:
StringStack();
//限定参数在函数体中不可被改变
void push(const string* s);
const string* pop();
//尝试去更改
const string* change(string* s,const string* ss);
};
const string* StringStack::change(string* s,const string* ss)
{
ss=s;
return ss;
}
StringStack::StringStack():index(0)
{
memset(stack,0,size * sizeof(string*));
}
void StringStack::push(const string* s)
{
if(index<size)
{
//改变传进来的常量
s=change(test,s);
//在汇编中可以看出:
0x0137E1C0 68 52 1d 00 63 72 65 61 6d 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 0f 00 00 00 00 00 00 00 b0 52 1d 00 72 69 70 70 hR..cream.......................?R..ripp
0x0137E1E8 6c 65 00 00 00 00 00 00 00 00 00 00 06 00 00 00 0f 00 00 00 00 00 00 00 f8 52 1d 00 6c 65 6d 6f 6e 00 00 00 00 00 00 00 le......................?R..lemon.......
0x0137E210 00 00 00 00 05 00 00 00 0f 00 00 00 00 00 00 00 40 53 1d 00 73 6f 72 62 65 74 00 00 00 00 00 00 00 00 00 00 06 00 00 00 ................@S..sorbet..............
0x0137E238 0f 00 00 00 00 00 00 00 88 53 1d 00 72 6f 63 6b 79 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 0f 00 00 00 00 00 00 00 ........?S..rocky.......................
0x0137E260 d0 53 1d 00 66 75 64 67 65 00 00 00 00 00 00 00 00 00 00 00 05 00 00 00 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 ?S..fudge...............................
0x0137E288 01 00 00 00 d8 22 1d 00 88 51 1d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ....?"..?Q..............................
0x0137E2B0 00 00 00 00 00 00 00 00 00 4c cc 0f 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 .........L?.............................
stack[index++]=s;
}
}
//限定函数的返回值不可被更新。
const string* StringStack::pop()
{
if(index>0)
{
const string* rv =stack[--index];
stack[index]=0;
return rv;
}
return 0;
}
string iceCream[]=
{
"cream","ripple","lemon","sorbet","rocky","fudge",
};
const int iCsz=sizeof iceCream / sizeof *iceCream;
int main()
{
StringStack ss;
for(int i=0;i<iCsz;i++)
{
ss.push(&iceCream[i]);
}
const string* cp;
while((cp=ss.pop())!=0)
// ss已经指向了test;所以输出的都是test;
cout<<*cp<<endl;
}