在我的头文件的执行情况,我有这样的:重载函数
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
参数省略完全相同。有没有办法压缩这个,还是我必须有一个函数原型和每个表单的定义?
这是否消除了第二个定义,第二个原型或两者? – Maxpm 2010-12-17 17:48:09
它消除了第二个原型及其定义。在这种情况下,你只有一个功能(因此只有一个原型和一个定义)。请注意,您只为头文件中的原型定义了可选参数的默认值。 – Flinsch 2010-12-17 17:53:37