C++-const修饰指针时类型识别方法

多才多艺的const,修饰指针的的功能非常难辨认,总结出一个方法:用类似于函数的方式记忆

1、const修饰函数【这种形式非常好识别】

const int* getData();    //返回值为常量[指向的对象]
int getData() const;     //函数本身为“常量”[函数不能修改类属性]

可以看到函数对象[getData]左边的const用于定义返回值为常量;

函数对象右边的const定义函数本身为常量。

2、根据const修饰函数模式去理解const修饰指针

假设类型为T,T*就是声明一个T类型的指针,当加上const一起工作时:

T*左边的const代表返回值也就是指向的值为const;

T*右边的const代表指针本身是const;

T*左右两边都有const代表值和指针都是const。

代码:

char greeting[] = "hello";
char* p = greeting;             //non-constpointer,non-const data
const char* p  =  greeting;     //non-constpointer,const data
char* const p = greeting;       //constpointer,non-const data
const char* const p = greeting; //constpointer,const data


原文链接: https://www.cnblogs.com/judes/p/15779996.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/184068

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 上午10:38
下一篇 2023年2月12日 上午10:39

相关推荐