简体   繁体   中英

c++ weird function

I don't know why it is changing third sign to w, this is very weird notation(i know why it is third one, but I don't know how it works).

using namespace std;
char napis[] = "ALICE";

char& which(int n){
    return napis[n];
}

int main(){
which(2) = 'w';
cout << napis << endl;
return 0;
}

Get a book, seriously.

which() returns reference to third element of the array; by which(2) = ... you assign value to variable referenced by that reference.

But to understand how it really works you have to understand what a reference is - which is explained in that book you should get.

Since the string "ALICE" is an array of chars, and an array starts at index 0, the 2nd index is the third char in the string.

You are also returning a reference instead of a copy of the char, this is why the string changes if you change it's value.

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