读C++ Common Knowledge(三)
sshong 发表于2007年12月8日 13:42:00 更新于2008年3月21日 19:19:00
7.常指针和指向常量的指针(const pointers) and pointers to const
区别准则:*左边的const都是指向的对象是常量,而*右边的const是指针的指向不能被改变。
const T *pct= new T;//ptr to const T
T* const pct=new T;//const ptr to T
一个指向常量的指针可能指向是一个非常量对象,但是一个指向非常量的指针不能指向一个常对象。

const T *pct=new T;//ptr to const and refer to a non-const object
const T acT;
T *pt=&acT;//error,ptr to non-const cann't refer to a const object
8.指针的指针(pointers to pointer)
尽量减少使用指针的指针作为函数形参,尽量使用指针的引用!
对比如下:
void scan(const char **p, char c)
{
  while(**p && **p !=c)
    ++*p;
}
void scan(const char *&p,char c)
{
  while(*p && *p!=c)
   ++*p;
}
char s[]="hi, i am sshong";
const char *cp=s;
scan(cp, ',');
标签:无分类:C++阅读:3393
评论
暂无评论
添加评论
您的大名,限长10汉字,20英文(*)
电子信箱(*)
您的网站
正文,限长500汉字,1000英文(*)
验证码(*) 单击刷新验证码
联系我
博客订阅