C++ const用法,面試前你必須要知道主要用法。

本文主要介绍const修饰符在C++中的主要用法,下面会从两个方面进行介绍:类定义中使用const

非类定义中使用const

1. 非类定义中使用const

非类定义中使用const是指:在除了类定义以外的场景中使用const。

1.1 变量
<code>

const

int

a =

1

;

int

b =

2

;

const

int

&b = a;

const

int

*p = &a;

int

*

const

q = &b;

const

int

*

const

s = &a; /<code>

顶层const:变量本身是个常量底层const:变量所指向的对象是个常量用于声明引用的const都是底层const

1.2 函数
<code>

int

fun1

(

const

int

a)

;

const

int

fun2

(

int

a)

;

const

int

&

fun3

(

int

&a)

;

const

int

&

fun4

(

int

a)

; /<code>

Tips:

  1. 引用只是一个变量的别名
    不是对象,因此引用不会占用存储空间
  2. 调用一个返回引用的函数得到左值,其他返回类型得到右值

2. 类定义中使用const

2.1 类成员
<code>

class

Test

{

public

:

Test

():

a

(

10

){}

void

display

();

private

const

int

a

; }; /<code>
  1. 类定义中不能进行初始化,因为在头文件中定义只是一个声明,并没有分配真正空间,因此变量是不存在的,因此是不能赋值的。
  2. 在类定义外部,const定义的变量是不能被赋值

问题:类定义中不能赋值,类定义外部也不能赋值,但是又必须赋值,这可如何是好?

解决方案:

  1. 在构造函数后的参数初始化列表中初始化
  2. 将const变量同时声明为 static 类型进行初始化
<code>

class

Test

{

public

: Test():a(

10

){}

void

display

()

;

private

const

int

a; }; /<code>
2.2 类成员函数
<code>

class

Test

{

public

:

void

display

()

;

void

display

()

const

;

private

const

int

a; }; /<code>

Tips:成员函数都有一个额外的隐式参数this,this的值是调用该函数的对象地址,因此this是一个指针。普通成员函数的this指针类型是:Test* const thisconst成员函数的this指针类型是:const Test* const this

<code>

Test

t1

;

const

Test

t2

;

t1

.display

();

t2

.display

(); /<code>

因为两个函数的this指针类型不同,所以display有两个重载函数。

作用:为了在函数体内禁止修改对象,可以通过定义const成员函数来实现。

Others:下图是截自C++ primer中的片段,请重点关注两个display函数的返回值:display 普通成员函数的返回值是:普通引用display const成员函数的返回值是:常量引用造成返回值不同的原因就是:this指针类型不同

C++ const用法,面试前你必须要知道主要用法。


感谢观看,点个赞呗~


分享到:


相關文章: