2010-12-17 89 views
0

在我的头文件的执行情况,我有这样的:重载函数

std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse); 
std::string StringExtend(const std::string Source, const unsigned int Length); 

在我的cpp文件,我有这样的:

std::string Cranberry::StringExtend(const std::string Source, const unsigned int Length, const bool Reverse) 
{ 
    unsigned int StartIndex = (Source.length() - 1) * Reverse; 
    short int Increment = 1 - (Reverse * 2); 

    int Index = StartIndex; 

    std::string Result; 

    while (Result.length() < Length) 
    { 
     if (Reverse) Result = Source.at(Index) + Result; 
     else Result += Source.at(Index); 

     Index += Increment; 

     if (!InRange(Index, 0, Source.length() - 1)) Index = StartIndex; 
    } 

    return Result; 
} 

std::string Cranberry::StringExtend(const std::string Source, const unsigned int Length) 
{ 
    return StringExtend(Source, Length, false); 
} 

正如你可以看到,函数的第二种形式与Reverse参数省略完全相同。有没有办法压缩这个,还是我必须有一个函数原型和每个表单的定义?

回答

7

使用Reverse参数的默认参数。

std::string StringExtend(const std::string & Source, unsigned int Length, bool Reverse = false);

摆脱第二功能:

std::string StringExtend(const std::string & Source, unsigned int Length);

2

您可以为“可选”参数设置默认值,如const bool Reverse = false

+0

这是否消除了第二个定义,第二个原型或两者? – Maxpm 2010-12-17 17:48:09

+1

它消除了第二个原型及其定义。在这种情况下,你只有一个功能(因此只有一个原型和一个定义)。请注意,您只为头文件中的原型定义了可选参数的默认值。 – Flinsch 2010-12-17 17:53:37

1

是对布尔参数使用默认参数。例如std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse = false);然后不需要第二个功能