In C++, what does & mean after a function's return type?

后端 未结 11 1445
情歌与酒
情歌与酒 2020-11-29 23:49

In a C++ function like this:

int& getNumber();

what does the & mean? Is it different from:

int getNumb         


        
11条回答
  •  温柔的废话
    2020-11-30 00:16

    It means that it is a reference type. What's a reference?

    Wikipedia:

    In the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with pointers and C++ references being specific reference datatype implementations. The declaration of the form:

    Type & Name

    where is a type and is an identifier whose type is reference to .

    Examples:

    1. int A = 5;
    2. int& rA = A;
    3. extern int& rB;
    4. int& foo ();
    5. void bar (int& rP);
    6. class MyClass { int& m_b; /* ... */ };
    7. int funcX() { return 42 ; }; int (&xFunc)() = funcX;

    Here, rA and rB are of type "reference to int", foo() is a function that returns a reference to int, bar() is a function with a reference parameter, which is reference to int, MyClass is a class with a member which is reference to int, funcX() is a function that returns an int, xFunc() is an alias for funcX.

    Rest of the explanation is here

提交回复
热议问题