C++ const

xiaoxiao2022-06-12  37

一、cosnt修饰常量

const int a = 5;与int const a = 5;

以上两者等同,且变量必须初始化(除非使用extern关键字,指明变量为外部连接,在程序的其他部分进行了定义)

二、const修饰指针变量时:

根据const相对*的位置判断const修饰是指针的值还是指针的地址。

一、const位于*左边,表示指针所指数据是常量,不能修改其指向的数据的值,指针地址本身可以修改指向其他内存单元 。

cosnt int* m      int const *m这两者是等同的

下面这种试图修改指针指向的值的写法会提示错误。

const int* m1 = new int(10); int* test = new int(20); *m1 = 2;

下面这种修改指针指向地址的做法是正确的。

const int* m1 = new int(10); int* test = new int(20); m1 = test;

二、const位于*右边,表示指针地址是常量,即指向地址是固定的,不能指向其它地址,指针指向地址的数据可以进行修改。

int* const m

下面这种写法,试图修改指针指向地址会提示错误。

int* const m1 = new int(10); int* test = new int(20); m1 = test;

 如果修改指针指向的值,则可以成功。

int* const m1 = new int(10); int* test = new int(20); *m1 = *test;

三、两个const,*左右个一个,则表示指针值和地址都不能修改。

cosnt int* const m

int const* const m

三、const修饰成员函数

在类中使用时:

1.const修饰的成员函数不能修改任何的成员变量

2const成员函数不能调用非const函数,因为非cosnt函数可能修改成员变量

四、const放在函数前方和后方

const一般放在函数的后方,表示函数时只可读的,不能修改成员变量

如:int Gety() const

放在函数前面,修饰的是函数返回的指针值,表示返回的指针指向值是常量

如:const int* GetPosition()

转载请注明原文地址: https://www.6miu.com/read-4932266.html

最新回复(0)