仅将一个整数发送到一个需要两个整数的函数
Send only one integer to a function that takes two integers
我对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;
}
你不能。您必须为函数具有的每个参数提供参数。如果有默认参数,您可能不需要明确执行此操作,但这仍然提供了该参数的参数。
相关文章:
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 当我们从/tp地址中添加/减去一个整数时会发生什么
- 如何将一个数组值合并为一个整数c++
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 给定一个整数数组,需要在Max_Heap上运行操作。得到错误"segmentation fault",有什么想法吗?(C++)
- 我可以将迭代器递增一个整数吗?
- 有没有办法生成一个包含平方的序列,这些平方加起来就是一个整数平方?
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 为什么将两个浮点数相加会得到一个整数C++?
- 编写一个读取五个整数并执行一些任务的C++程序
- 如果我们在其中输入一个整数,则字符会给出整数作为输出,但是当分配给它一个整数时,这不会发生。为什么?
- 给枚举一个整数,并在 C++ 中将其相关值作为字符串获取
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 按升序输出整数时,将最后一个整数放在新行上
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 我在c++中遇到了一个奇怪的错误,其中一个计算2个小整数加法的语句溢出到一个长值中
- 如何在C++中将一个值拆分为一个十进制整数
- 给定一个整数 N>0,区间 [0, 2^N) 中有多少个整数正好有 N-1 个设置位?编写一个返回正确答案的简短函数
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 将整数范围映射到另一个范围