简体   繁体   中英

Return value int&

I have a code like this.

#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}

The output I am getting is

0
1 1
1 2

Now the function abc returns an integer reference. So the statement int f=abc(); should point integers f and c to the same address. But why the statement f++ is not affecting the value of c?

int &f = abc();

因为您的f不是引用,它只是一个分配了c值的变量,您应该像上面那样编写它。

That's because while abc() returns an int by reference, f doesn't "grab" this reference, but rather grabs the value the returned reference points to. If you want f to grab the reference, you need to define it as a reference type.

Do it like this:

#include <iostream>
using namespace std;

int c=0;
int& abc()
{
    c++;
    return c;
}

int main()
{
    cout << c << endl;
    int &f = abc();
    cout << c << " " << f << endl;
    f++;
    cout << c << " " << f << endl;
}
int f = abc();
^^^ // This type is 'int' not 'int&'

You're type for f is int which is no the same as int& and results in creating a copy. Therefore, instead of f being a reference to c it is a separate and distinct value that is initialized to the same value as stored in c when it is returned from abc .

Yes abc() returns a reference. But f is just an integer variable. Therefore what int f=abc() does is assigning the value of c to f . When you call f++ it only change the f variables value. It does not change the value of c . because f is not a pointer.

In following code: int f = abc() f is a copy of the value of c , these two values are distinct. When you perform ++f you are incrementing the copy f which will have no effect on c . When you do the following: int &f = abc() you are creating a reference variable f which is bound to the value of c and hence as f is an alias for the variable c , any changes made to f are made to c .

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