What is the meaning of & in c++?

前端 未结 6 711
走了就别回头了
走了就别回头了 2020-12-03 16:50

I want to know the meaning of & in the example below:

class1 &class1::instance(){

///something to do

}
相关标签:
6条回答
  • 2020-12-03 16:55

    This means your method returns a reference to a method1 object. A reference is just like a pointer in that it refers to the object rather than being a copy of it, but the difference with a pointer is that references:

    • can never be undefined / NULL
    • you can't do pointer arithmetic with them

    So they are a sort of light, safer version of pointers.

    0 讨论(0)
  • 2020-12-03 17:00

    Its a reference (not using pointer arithmetic to achieve it) to an object.

    0 讨论(0)
  • 2020-12-03 17:06

    It means that the variable it is not the variable itself, but a reference to it. Therefore in case of its value change, you will see it straight away if you use a print statement to see it. Have a look on references and pointers to get a more detailed answer, but basecally it means a reference to the variable or object...

    0 讨论(0)
  • 2020-12-03 17:12

    The & operator has three meanings in C++.

    • "Bitwise AND", e.g. 2 & 1 == 3
    • "Address-of", e.g.: int x = 3; int* ptr = &x;
    • Reference type modifier, e.g. int x = 3; int& ref = x;

    Here you have a reference type modifier. Your function class1 &class1::instance() is a member function of type class1 called instance, that returns a reference-to-class1. You can see this more clearly if you write class1& class1::instance() (which is equivalent to your compiler).

    0 讨论(0)
  • 2020-12-03 17:18

    It returns a reference to an object of the type on which it was defined.

    0 讨论(0)
  • 2020-12-03 17:21

    In the context of the statement it looks like it would be returning a reference to the class in which is was defined. I suspect in the "Do Stuff" section is a

    return *this;
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题