One, plus inC + + overloading a bit of using a global function is the ability to use cascading methods for addition operations.
Fraction a,b,c,d,e; A=b+c+d+e;
If the member function
1. The this pointer of the returned b is used for the following variables respectively, so it is a modification to b ;
2, if the return of a new variable, the above cascading problem seems to be resolved.
3, the problem is that if there is an implicit type conversion, and the first argument is a type that needs to be converted, you may not find the member function of the definition, so you can use a global approach to the problem
Second, the return value needs a value, not a reference
To return a reference from a local function, consider two scenarios.
1. If the local variable is applied on the stack, then when the function returns, the pointer is rolled back, which is when the other function executes again, the original value may be rewritten. The memory here is reused, resulting in an unknown nature.
Here is an example:
int& func () { int m=9; return m;} void Func2 () { int i=1; cout << "F2:" << i << Endl;} int main () { int& fp=func (); Func2 (); cout<<fp<<endl; return 0;} Output is:1
Apparently this caused a memory rewrite
Sometimes we write like this
int main () { int fp=func (); Func2 (); cout<<fp<<endl; return 0;}
This is the output or 9, because this is the FP is just a value, not a reference
2. If the value returned is requested on the heap
Fraction a,b,c,d,e; A=b+c+d+e;
Then I will cause a memory leak here.
B+c Returns a new memory, but the pointer is lost after executing (b+c) +d , so the delete is not possible, andThe subsequent situation is similar.
Understanding-plus reload to use global function + return value non-reference