0

所以这是我的代码,我知道按值调用的输出是

Here is f
main: z = 15 

如果一种语言使用名称调用而不是值调用会怎样?

int f() {
    cout << "Here is f" << endl;
    return 5;
}
int g(int a) {
    int x = a;
    int y = 2 * a;
    return x + y;
}
int main() {
    int z = g(f());
    cout << "main: z = " << z << endl;
}
4

2 回答 2

1

你可以这样做:

#define f(n) (cout << "Here is f" << endl, n)

#define g(n) (n + 2 * n)

int main()
{
    int z = g(f(5));
    cout << "main: z = " << z << endl;
}

的“主体”f()被评估两次,因为它在g().

于 2018-05-17T20:48:31.097 回答
1

您可以使用 模拟名称调用std::function,并调整语法:

int f() {
    std::cout << "Here is f" << std::endl;
    return 5;
}

int g(std::function<int()> a) {
    int x = a();
    int y = 2 * a();
    return x + y;
}
int main() {
    int z = g(f);
    cout << "main: z = " << z << endl;
}

带输出:

Here is f
Here is f
main: z = 15

演示

于 2018-05-17T21:09:22.197 回答