C++ **(指针的指针)和*&(指针的引用)——个人理解

一、解释*和&

&在变量定义区,表示引用 int &x ;
&在变量操作区,表示取地址符 int x=10, *p=&x ;
*在变量定义区,表示指针 int *x ;
*在变量操作区,表示解引用 int *x ;cout<<*x ;

二、解释**和*&

  • **是指 指针的指针
  • *&是指 指针的引用

注意:只有对指针的引用,没有指向引用的指针!(因为引用本身不是对象)

三、代码解释传单指针、传双指针、传指针的引用

具体使用起来原理是相同的,请看代码:

  • 传单指针:
void onePointerFunc(int *pMyClass) 
{
    
     
   pMyClass = new int; 
}  

调用:

 int* p = new int; 
 onePointerFunc(p); 

调用onePointerFunc后,p没有指向新的对象。

  • 传双指针:
 void poiPointerFunc(int** pMyClass)
{
    
     
	*pMyClass = new int; 
}   

调用:

  int* p =new int;  
  poiPointerFunc(&p);

调用poiPointerFunc之后,p指向新的对象。

  • 传指针的引用:
void refPointerFunc(int *&pMyClass)
{
    
     
   pMyClass = new int; 
}   

调用:

 int* p = new int;
 refPointerFunc(p); 

调用refPointerFunc之后,p指向新的对象。

其实,指针的引用和指针的指针是一码事,只是语法有所不同。传递的时候不用传p的地址&p,而是直接传p本身。

四、参考资料

以上内容参考于:
C++中引用,指针,指针的引用,指针的指针
C++ 函数参数中“ &代表什么? ”
C++之&和

猜你喜欢

转载自blog.csdn.net/weixin_48622537/article/details/111305840