both asterisk and ampersand in a parameter c++

坚强是说给别人听的谎言 提交于 2019-11-27 04:37:17

问题


I am reading a book about Binary Search Tree and something weird came up.

class BST
{
public:
   void insert(const Comparable & item)

private:
   BinaryNode *root;
   struct BinaryNode
   {
       Comparable element;
       BinaryNode *left;
       BinaryNode *right;
       BinaryNode(const Comparable & theElement, BinaryNode *lt, BinaryNode *rt) : 
          element(theElement), left(lt), right(rt) {}
   }
   void insert(const Comparable & item, BinaryNode * & t) const;
};

The private insert function is helper function for public insert function, and private insert function looks for the right place to insert using recursion.

Part that I don't understand is BinaryNode * & t in the parameter. What does it mean? Pointer of the address of t?


回答1:


In your expression BinaryNode * & t)

            BinaryNode*                & t
           -------------              -----
            BinaryNode pointer        t is reference variable  

so t is reference to pointer of BinaryNode class.

Pointer of the address of t?

You are confused ampersand & operator in c++. that give address of an variable. but syntax is different.

ampersand & in front of some of variable like below:

BinaryNode b;
BinaryNode* ptr = &b;

But following way is for reference variable (its simple not pointer):

BinaryNode b;
BinaryNode & t  = b; 

and your is like below:

BinaryNode b;
BinaryNode* ptr = &b;
BinaryNode* &t  = ptr;  



回答2:


It's reference to pointer, you can change pointer in this function and it will changed outside. Simple example http://liveworkspace.org/code/1EfD0Q$8



来源:https://stackoverflow.com/questions/14314640/both-asterisk-and-ampersand-in-a-parameter-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!