Reference functions in C++
I have a function that gives me the error "cannot convert from 'int' to 'int &'" when I try to compile it.
int& preinc(int& x) {
return开发者_如何学运维 x++;
}
If I replace x++ with x, it will compile, but I'm not sure how that makes it any different. I thought that x++ returns x before it increments x, so shouldn't "return x++" be the same as "return x" with regard to what preinc returns? If the problem is with the ++ operator acting on x, then why won't it generate any error if I put the line "x++" before or after the return statement, or replace x++ with ++x?
x++
creates a temporary copy of the original, increments the original, and then returns the temporary.
Because your function returns a reference, you are trying to return a reference to the temporary copy, which is local to the function and therefore not valid.
Your function does two things:
- Increments the
x
that you pass in by reference - Returns a reference to the local result of the expression
x++
The reference to a local is invalid, and returning anything at all from this function seems completely redundant.
The following is fixed, but I still think there's a better approach:
int preinc(int& x) {
return x++; // return by value
}
Yes, x++
returns x before it is incremented. Therefore it has to return a copy, the copy is a temporary and you can only pass temporaries as constant references.
++x
on the other hand returns the original x
(although incremented), therefore it will work with your function.
精彩评论