Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

Affecting a function to another function in c++

So there's this code am trying to understand:

#include <iostream>

using namespace std;

int x = -2;

int h(int &x) {
  x = 2 * x;
  return x;
}

int g(int f) { return x; }

int &f(int &x) {
  x += ::x;
  return x;
}

int main() {
  int x = 6;
  f(::x) = h(x);
  cout << f(x) << endl;
  cout << g(x) << endl;
  cout << h(x) << endl;
  return 0;
}

Output:

24
12
48

I understood the function of the scope resolution operator (::), which is to use the global int x, but the part that i don't understand is this part: f(::x) = h(x); and this one: int g(int f){return x;}

So what am trying to understand is what happens step by step when these instructions get executed.

question from:https://stackoverflow.com/questions/65951841/affecting-a-function-to-another-function-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The line

f(::x) = h(x);

is equivalent to

operator=(f(::x), h(x));

First, one of the functions f or h are called and the returned value is passed to operator=. Then the other function is called and the returned value is passed to operator=. The order is irrelevant because in either case f changes the value of global x to -4 and returns a reference to it and h changes local x (local in main) to 12 and returns its value. Then the value 12 is assigned to global x.

The line

int g(int f) { return x; }

defines a function that returns the value of global x.

Maybe using different variable names helps understanding:

#include <iostream>

using namespace std;

int globalX = -2;

int h(int &hX) {
  hX = 2 * hX;
  return hX;
}

int g(int f) { return globalX; } // f is unused

int &f(int &fX) {
  fX += ::globalX;
  return fX;
}

int main() {
  int mainX = 6;
  f(::globalX) = h(mainX);
  cout << f(mainX) << endl;
  cout << g(mainX) << endl;
  cout << h(mainX) << endl;
  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...