2016-12-04 73 views
0

我是新鲜的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; 
} 

} 

然后到这里,我们有我们的主要功能,我们称之为测试:在某些情况下,只是想叫test(1) 测试(1,8),这是很好的,但如果我?如果我不想给这个函数提供两个整数,因为我希望它只为int one做什么?我想通过简单地做test(1,NULL)test(NULL,10)有一个解决方法,但这是丑陋的权利?

必须有办法,我知道我的例子很糟糕,但我希望你明白我的观点。

+2

[函数重载](https://en.wikipedia.org/wiki/Function_overloading) – Drop

+0

您可以为函数写入一个重载,该函数接受一个参数。查找函数重载。 – DeiDei

+0

@Drop感谢您的帮助! –

回答

3

一种方式是提供一个默认的参数,第二个:

void test(int one, int two = 0) 

然后,如果你只用一个参数调用它那么第二个参数假定的默认值。

另一种方法是重载函数:

void test(int one) 

这样做,你可以写具体的行为,当一个单一的参数传递时的优势。

+0

这并没有真正区分是否给出了第二个参数的值。 –

+0

是的,这个答案是不完整的。 – Bathsheba

-1

你不能。您必须为函数所具有的每个参数提供参数。如果存在默认参数,您可能不需要明确地这样做,但仍然为该参数提供参数。

0

如果需要局部评价,看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; 
} 
+0

在问题中我没有看到任何证据表明这是所谓的。 –

+0

“..如果我在某些情况下只是想打电话测试(1),“对我来说是一个很好的指示。” –

+0

_“因为我希望它只做一个int的东西”_你必须阅读整个问题,而不是只是其中的一部分:) –

0

有2个选项:

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

这给功能两种因此调用测试的默认值(2)将意味着测试函数将以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) { 
    /* ... */ 
} 

如果您有任何问题随时问。

相关问题