您的位置:首页 > 编程语言 > C语言/C++

C++ const关键字用法详解

2013-07-31 09:38 656 查看
1const char*, char const*, char*const的区别问题几乎是C++面试中每次都会有的题目。

事实上这个概念谁都有只是三种声明方式非常相似很容易记混。

Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:

把一个声明从右向左读。( * 读成 pointer to )

char * const cp;

cp is a const pointer to char 

const char * p;

p is a pointer to const char;

char const * p; 同上

因为C++里面没有const*的运算符,所以const只能属于前面的类型。 C++标准规定,const关键字放在类型或变量名之前等价的。

const int n=5; //same as belowint const m=10;

char ** p1; //p1 is pointer to pointer to char

const char **p2;//p2 is pointer to pointer to const char

char * const * p3;//p3 is pointer to const pointer to char

const char * const * p4;//p4 is pointer to const pointer to const char

char ** const p5;//p5 is const pointer to pointer to char

const char ** const p6;//p6 is const pointer to pointer to const char

char * const * const p7;//p7 is const pointer to const pointer to char

const char * const * const p8;//p8 is const pointer to const pointer to const char  

2. const修饰函数参数

const修饰函数参数是它最广泛的一种用途,它表示函数体中不能修改参数的值(包括参数本身的值或者参数其中包含的值)。它可以很好

void function(const int Var); //传递过来的参数在函数内不可以改变(无意义,因为Var本身就是形参)

void function(const char* Var); //参数指针所指内容为常量不可变

void function(char* const Var); //参数指针本身为常量不可变(也无意义, 因为char* Var也是形参)

参数为引用,为了增加效率同时防止修改。

修饰引用参数时:

void function(const Class& Var);//引用参数在函数内不可以改变

void function(const TYPE& Var); //引用参数在函数内为常量不可变

3. const 修饰函数返回值

const修饰函数返回值其实用的并不是很多,它的含义和const修饰普通变量以及指针的含义基本相同。

(1) const int fun1() 这个其实无意义,因为参数返回本身就是赋值。

(2) const int * fun2()

调用时 const int *pValue = fun2();

我们可以把fun2()看作成一个变量,const pointer to an int ,即指针内容不可变。

(3) int* const fun3()

调用时 int * const pValue = fun2();

我们可以把fun2()看作成一个变量,函数返回const pointer to an int ,即指针本身不可变。

返回值为const可以阻止返回值作为左值

4. const修饰类对象/对象指针/对象引用

const修饰类对象表示该对象为常量对象,其中的任何成员都不能被修改。对于对象指针和对象引用也是一样。

const修饰的对象,该对象的任何非const成员函数都不能被调用,因为任何非const成员函数会有修改成员变量的企图。

例如:

class AAA

{

void func1();

void func2() const;

}

const AAA aObj;

aObj.func1(); ×

aObj.func2(); 正确

const AAA* aObj = new AAA();

aObj->func1(); ×

aObj->func2(); 正确

5. const修饰成员变量

const修饰类的成员变量,表示为成员常量,不能被修改,同时它只能在初始化列表中赋值。

class A

{



const int nValue; //成员常量不能被修改



A(int x): nValue(x) {}; //只能在初始化列表中赋值

}

6. const修饰成员函数

const修饰类的成员函数,则该成员函数不能修改类中任何非const成员函数。一般写在函数的最后来修饰。

class A

{



void function()const; //常成员函数, 它不改变对象的成员变量. 也不能调用类中任何非const成员函数。

}

对于const类对象/指针/引用,只能调用类的const成员函数,因此,const修饰成员函数的最重要作用就是限制对于const对象的使用。

7. const常量与define宏定义的区别

(1) 编译器处理方式不同

define宏是在预处理阶段展开。

const常量是编译运行阶段使用。

(2) 类型和安全检查不同

define宏没有类型,不做任何类型检查,仅仅是展开。

const常量有具体的类型,在编译阶段会执行类型检查。

(3) 存储方式不同

define宏仅仅是展开,有多少地方使用,就展开多少次,不会分配内存。

const常量会在内存中分配(可以是堆中也可以是栈中)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 笔试面试 面试 CC++