如何给一个参数一个默认值,该默认值由其他参数的函数确定 [英] How to give an argument a default value determined by a function of the other arguments

查看:99
本文介绍了如何给一个参数一个默认值,该默认值由其他参数的函数确定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有多个参数的C ++函数中,我希望其中一个参数具有默认值,该默认值本身是其他参数的函数。例如,

In a C++ function with multiple arguments, I would like one of the arguments to have a default value which is itself a function of the other arguments. For example,

int f1( int m );
int f2( int n1, int n2 = f1( n1 ) ) {
    // Do stuff with n1 and n2
}

这不会编译,但是希望它可以弄清楚我想要的函数f2的行为。它的调用方应该能够手动为其传递n2的值,但是默认情况下,应通过在n1上调用f1来确定n2的值。对于如何最好地实现(或至少近似)此行为有什么建议?

This won't compile, but hopefully it makes clear the behavior I want for the function f2. Its caller should be able to manually pass it a value for n2, but by default the value of n2 should be determined by calling f1 on n1. What are some suggestions for how best to implement (or at least approximate) this behavior?

推荐答案

而是重载函数:

int f1( int m );
int f2( int n1, int n2 ) {
    // Do stuff with n1 and n2
}
int f2( int n1 ) {
    return f2( n1, f1( n1 ) );
}

这篇关于如何给一个参数一个默认值,该默认值由其他参数的函数确定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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