避免函数重载

Avoiding function overloading

本文关键字:重载 函数      更新时间:2023-10-16

在下面的程序中,我有一个函数重载。一个只有一个参数,另一个有两个参数,还有一个有三个参数。在下面的示例中,它看起来很简单,因为函数不太长。如果函数很长,并且用不同的输入参数一次又一次地编写相同的函数看起来很难看怎么办?一种方法是variadic functions。如果我知道我的函数只需要1 2或3个输入参数variadic functions真的有必要吗?如果有,我该怎么做呢?注意:具有三个输入参数和两个输入参数的函数执行不同的计算。

#include <iostream>
using namespace std;
int function(int a, int b, int c)  // All the arguments are always of the same type
{
    return a*b*c;
}
int function(int a, int b)
{
    int c = a; // Always duplicate the first argument
    return a*b*c;  
}
int function(int a)
{
    int b = a, c = a; // Always duplicate the first argument
    return a*b*c;
}
int main()
{
    cout<<function(2,3,4)<<"n"<<function(2,3)<<"n"<<function(2);
    cin.ignore();
    return 0;
}
编辑:

对于歧义,伙计们很抱歉。我编辑了代码

首先,如果你的函数又长又丑,你应该把它重构成一组更小的函数甚至类。

对于你的实际问题,我会像这样使用重载函数作为包装器:

int function(int a, int b, int c)
{
  return a * b * c;
}
int function(int a, int b)
{
  return function(a, b, a);
}
int function(int a)
{
  return function(a, a, a);
}

这避免了代码重复和对可变函数的任何需要。对于可变函数,您将失去静态类型检查,因此它们非常容易出错。

任何使用可变变量函数的解决方案都会更糟:首先,可变变量函数不知道调用了多少参数,也不知道调用了哪种类型,您需要额外的参数才能知道。

我认为解决方案是只使用一个带有签名函数(int,int,int)的函数。

如果你想复制其他变量的行为,你可以显式地做,用function(a,b,a)代替function(a,b)。

在您的问题中,您声明多次编写相同的长函数是令人厌烦的,并且三输入和双输入版本不同。是哪种情况?

  • 如果它们在做同样的事情,只需从另一个调用一个。通常情况下,具有较少参数的函数调用其直接上级函数时,会在链上再增加一个参数,或者所有重载调用单个参数最多的版本。

  • 如果它们在做不同的事情,你可能没有理由让它们过载。将它们命名为不同的名称可能会使事情变得清晰,并减轻"两次编写相同函数"的感觉。

  • 如果它们做类似的事情,即落在上面两种情况之间的某个地方,你可能需要额外的函数来分解原始的,重载的函数的相同部分。

你的例子属于第一类:

int function(int a, int b, int c)  // All the arguments are always of the same type
{
    return a*b*c;
}
int function(int a, int b) // Always duplicate the first argument
{
    return function(a,b,a);  
}
int function(int a) // Always duplicate the first argument
{
    return function(a,a);
//  return function(a,a,a); //might make more sense depending on actual function/variable names
}

如果计算是不同的,是不同的函数,你没有任何理由避免重载。

即使calc是相同的,你应该避免Variadic_function,它可能会提供很多错误(与类型,参数计数等)

此外,尝试将这3个函数作为1个变量,并说它不那么难看。我会笑的

切换为参数计数也是运行时(如varidiac_function)比编译时更糟糕

看起来你应该用数组来代替:

void Function(int* items, int count)
{
    int result = 1;
    for(int i = 0; i < count; i++)
    {
        result *= items[i];
    }
}