1.const 修饰变量
对于一个字符指针的定义char * p;加上const关键字时无非有三种方法,即把const放在前中后三个位置。那么他们之间有什么区别呢?
1 const char * p1;//表示p1指向了的字符串不可更改
2 char const * p2;//同上
3 char * const p3;//表示p2指针的指向不可更改
注意1和2的意义完全相同,只是不同的程序员具有不同的编码习惯,我们要熟悉所有的这三种用法,下面给出一段代码,来说明他们三个的区别:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <limits.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
const char * p1 = new char [10]();
for( int i = 0 ; i < 10 ; i++ )
{
cout<<p1[i]<<endl;
}
p1[0] = 'a';//错误!const char * p指向一个不可改变的对象
cout<<p1[0]<<endl;
char const * p2 = new char[10];
p2[0] = 'a';//错误!同上
cout<<p2[0]<<endl;
char ch[5] = "abcd";
delete [] p1;
p1 = ch;//正确 指针的值可以修改
cout<<p1<<endl;
char * const p3 = new char[100];
p3[0] = 'a';//正确!
cout<<p3[0];
delete [] p3;
p3 = ch;//错误 指针的值不可以修改
cout<<p3<<endl;
}
在第18行和第22行中,由于指针所指向的对象不可修改,因此会出现错误,而在35行处其指针的指向不可修改,因此不可把它指向另一个地址。
2.const 修饰函数
const不仅可以修饰变量,也可以修饰函数,当const修饰函数,例如[]符重载操作, int & operator [](int n) 时有两个位置可以放置:
1) const int & operator[](int n);
前者指其返回值不可修改,例如对于一个const对象 cint,我们不可以使用cin[0]=3,这种左值的方式对其进行赋值,因为其是一个const对象,应该不能够对其内部值进行修改。
而后者的意思是该[]操作符函数内部不对其对象内部进行修改,是一个const函数,如果其函数实现对内部成员进行了修改,则会报错。
对于一个[]操作符,我们往往使用重载的方式来实现其const版本和非const版本,在const版本中,如果对象定义为const其内部成员不可修改,否则可以自由修改。例如如下代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <limits.h>
#include <iostream>
using namespace std;
class MyIntArray
{
private:
static const int a = 100;
int p[a];
public:
MyIntArray()
{
for( int i = 0 ; i < a ; i++ )
{
p[i] = i;
}
}
const int & operator [](int n) const
{
return p[n];
}
int & operator [](int n)
{
return p[n];
}
};
int main(int argc, char *argv[])
{
MyIntArray array;//定义一个非const对象
cout<<array[20]<<endl;//输出20
array[20] = 6;//正确,调用非const版本的[]
cout<<array[20]<<endl;//输出6
const MyIntArray carray;//定义一个const对象
cout<<carray[20]<<endl;//输出20
carray[20] = 6;//错误!调用const版本的[]操作符
cout<<carray[20]<<endl;
}
对于一个非const对象array我们可以自由的把array[0]作为左值,而对于一个const对象array我们则不可以把其作为左值。由此可发现const的强大之处。