简体   繁体   中英

why reference is not a object,but it can be used with &?

like this code

int i = 42;
int *p = &i;
int *&r = p;
*r = 0;

The r is reference and is not a object, so why it can be used with * .

why reference is not a object

Because the that's how references are specified in the language.

The "r" is reference and is not a object,so why is can be used with "*".

Because the object that r refers to is a pointer, and you can use a pointer as an operand to the unary * operator.

A reference can be bound to things other than objects. Remember that a pointer is also an object. So a reference can be bound to a pointer too, or to even another reference. See for yourself with some throwaway code:

#include <iostream>

template<class T>
struct Foo
{
    Foo(T& t){
        std::cout << t << "\n";
    }
};

int main() {
    int object = 1;
    int* pointer = &object;
    int& reference = object;
    int*& reference_to_pointer = pointer;
    
    Foo<int> o1(object); // passing 'object' by reference
    Foo<int*> o2(pointer); // passing a pointer to 'object' by reference
    Foo<int&> o3(reference); // passing the reference to 'object' by reference
    Foo<int*&> o4(reference_to_pointer); // passing a reference to a pointer to 'object' by reference
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM