重载函数的实现

时间:2010-12-17 17:44:20

标签: c++ function overloading

在我的标题文件中,我有这个:

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参数完全相同。有没有办法压缩这个,或者我必须为每个表单都有一个函数原型和定义吗?

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分:2)

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

答案 2 :(得分:1)

是使用bool参数的默认参数。例如std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse = false);那么就不需要第二个函数

相关问题