哪个默认参数先求值,为什么? [英] Which default argument is evaluated first and why?

查看:89
本文介绍了哪个默认参数先求值,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个函数 funt1() funt2() funt3 ()

int funt1()
{
    cout<<"funt1 called"<<endl;
    return 10;
}

int funt2()
{
    cout<<"funt2 called"<<endl;
    return 20;
}

void funt3(int x=funt1(), int y=funt2())
{
    cout << x << y << endl;
}

我的 main

int main()
{
    funt3();
    return 0;
}

当我调用 funt3 c $ c>在我的 main()方法,为什么 funt1()先调用,然后 funt2()

When I am calling funt3() in my main() method, why is funt1() is called first, and then funt2()?

推荐答案

C ++标准没有定义,编译器特定。也就是说,你应该从不依赖一个未定义的行为实例。

C++ standard does not define that, so it's totally compiler-specific. That said, you should never rely on an instance of undefined behaviour.

编辑:如果你真的想保持函数调用作为默认参数减少每次我建议您执行以下操作时必须传递的参数数量:

if you really want to keep functions invocations as default parameters to reduce the numbers of parameters you have to pass each time I suggest you do the following:

void funt3(int x, int y)
{
    cout<<x<<y<<endl;
}

void funt3(int x)
{
    funt3(x, funt2());
}

void funt3()
{
    funt3(funt1());
}

这篇关于哪个默认参数先求值,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆