compiler error saying invalid initialization of reference of type something& from expression of type something*

前端 未结 3 684
花落未央
花落未央 2020-12-21 06:43

I have a function prototype like

test(something &)

and i am doing

something *ss = new something();

相关标签:
3条回答
  • 2020-12-21 07:23

    Your function expects a reference to something, and you are passing it a pointer to something. You need to de-reference the pointer:

    test(*ss);
    

    That way the function takes a reference to the object pointed at by ss. If you had a something object, you could pass that directly to:

    something sss;
    test(sss); // test takes a reference to the sss object.
    
    0 讨论(0)
  • 2020-12-21 07:33

    Your function expects a normal something object. You don't need to use a pointer here:

    something ss;
    
    test(ss);
    

    When your function signature looks like f(T&), it means that it accepts a reference to a T object. When the signature is f(T*), it means that it accepts a pointer to a T object.

    0 讨论(0)
  • 2020-12-21 07:36

    you are confused by reference and address of variable.

    If your function prototype is:

    test(something &)
    

    You could call it with something object:

    something ss;
    test(ss);
    

    You could call it with something pointer:

     something *ss = new something();
     test(*ss);
    

    If your function is:

    test(something *)
    

    You could call:

    something *ss = new something();
    test(ss);
    
    0 讨论(0)
提交回复
热议问题