Argument passing by reference to pointer problem

后端 未结 5 1186
你的背包
你的背包 2021-02-06 10:20

Every time I try to compile my code I get error:

cannot convert parameter 1 from \'int *\' to \'int *&\'

The test code looks like this:

5条回答
  •  醉酒成梦
    2021-02-06 11:01

    A reference to non-const cannot bind to an rvalue. The result of the & operator is an rvalue. Take a look at the difference between lvalues and rvalues or read a good C++ book.

    Also, in your context, you don't need to pass by reference. The following is OK as well:

    void set (int *val){
       *val = 10;
    }
    

    The reference would be needed if you were to do something like this;

    void set (int*& val){
       val = new int; //notice, you change the value of val, not *val
       *val = 10;
    }
    

提交回复
热议问题