简体   繁体   中英

What went wrong in this line?

for (int &x : v) {
        cout << (*x) << " ";
    }

It is giving me error that operation of '*' must be pointer but has type 'int'.

Well, just like it says, x is reference to int . A reference is not a pointer, and applying * to it does not make sense.

You should just say cout << x << " "; . A reference, unlike a pointer, is automatically dereferenced whenever it is used.

In addition to Nate's answer, I want to add that

..., no operator operates on a reference.

from the 4th of the C++ Programming Lannguage. I have this particular line highlighted in my copy of the book.

Like @Nate Eldredge said, a lvalue reference (in your case) always refers to the object it was initialized to denote. References are designed to simplify usage so that you do not need to worry about stuff like dereferencing or null pointers EVEN THOUGH they may be implemented using pointers.

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