简体   繁体   English

C ++怪异函数

[英]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). 我不知道为什么将第三个符号更改为w,这是非常奇怪的表示法(我知道为什么它是第三个符号,但是我不知道它是如何工作的)。

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; which()返回对数组第三元素的引用; by which(2) = ... you assign value to variable referenced by that reference. 通过which(2) = ...您可以将值分配给该引用所引用的变量。

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. 由于字符串“ ALICE”是一个字符数组,并且数组从索引0开始,因此第二个索引是字符串中的第三个字符。

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. 您还将返回引用而不是char的副本,这就是为什么如果更改字符串的值,字符串也会更改的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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