避免功能重载

0x0*_*0x0 2 c++ overloading variadic-functions

在下面的程序中,我有一个函数重载.一个只有一个参数,另一个有两个参数,另一个有三个.在下面的示例中,它看起来很简单,因为函数不会太长.如果函数很长并且使用不同的输入参数一次又一次地编写相同的函数看起来很难看.一种方法可以做到这一点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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

对不起那些含糊不清的人.我编辑了代码.

Dim*_*ima 11

首先,如果你的函数冗长而丑陋,你应该将它重构为一组较小的函数甚至是类.

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

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);
}
Run Code Online (Sandbox Code Playgroud)

这避免了代码重复和任何需要可变参数的功能.使用可变参数函数会丢失静态类型检查,因此它们非常容易出错.