仅将一个整数发送到一个需要两个整数的函数

Send only one integer to a function that takes two integers

本文关键字:整数 一个 两个 函数      更新时间:2023-10-16

我对C 很新鲜,并尝试使用功能进行不同的事物。我只是遇到了一个问题,或者是一个反思。

想象这个;我们有一个功能:

void test(int one, int two) {
if(one == 5) {
   cout << "one is 5" << endl;
}
if(two == 10) {
   cout << "two is 10" << endl;
}
if(one == 1 && two == 2) {
   cout << "they both are 1 and 2" << endl;
}
}

,然后在这里我们有我们的主要功能,我们调用测试:测试(1,8)这很好,但是如果我在某种程度上只想致电test(1)怎么办?如果我不想给两个函数的整数,因为我只想为int one做一些事情,该怎么办?我发现只需进行test(1,NULL)test(NULL,10)即可解决问题,但这很难吗?

一定有办法,我知道我的榜样很糟糕,但我希望你明白我的观点。

一种方法是向第二个提供默认参数:

void test(int one, int two = 0)

然后,如果您仅使用一个参数调用它,则第二个参数假定默认值。

另一种方法是超载该功能:

void test(int one)

这有一个优点,您可以为传递单个参数的情况写特定的行为。

有2个选项:

void test(int one, int two = -1) {
   /* ... */
}

这使该函数具有两个两个呼叫测试(2)的默认值,这意味着测试功能将以一个= 2和两个= -1的速度运行。这些默认值只有在函数定义中没有默认参数后没有变量的情况下才能起作用。

void testA(int one, int two = -1); // OK
void testB(int one, int two = -1, int three); // ERROR
void testC(int one, int two = -1, int three = -1); // OK

然后,另一个选项是超载此功能。超载意味着一个函数具有两个不同的定义。超载功能时,有一些规则需要遵循,主要是必须通过您喂养它们的参数来区分不同的过载。因此,在您的情况下,解决方案将是:

void test(int one) {
   /* ... */
}
void test(int one, int two) {
   /* ... */
}

如果您还有任何问题可以问。

如果您需要部分评估,请参见std :: bind:

#include <iostream>
#include <functional>
using namespace std::placeholders;
int adder(int a, int b) {
    return a + b;
}
int main() {
    auto add_to_1 = std::bind(adder, 1, _1);
    auto add_1_to = std::bind(adder, _1, 1);
    std::cout << add_1_to(2) << std::endl;
    std::cout << add_to_1(2) << std::endl;
    return 0;
}

你不能。您必须为函数具有的每个参数提供参数。如果有默认参数,您可能不需要明确执行此操作,但这仍然提供了该参数的参数。

相关文章: