Implementation of Overloaded Functions
In my header file, I have this:
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);
In my cpp file, I have this:
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);
}
As you can see, the second form of the function is the exact same t开发者_如何学Pythonhing with the Reverse
argument omitted. Is there a way to condense this, or do I have to have a function prototype and definition for each form?
Use a default parameter for your Reverse
parameter.
std::string StringExtend(const std::string & Source, unsigned int Length, bool Reverse = false);
Get rid of the second function:
std::string StringExtend(const std::string & Source, unsigned int Length);
You could set a default value for the "optional" parameter, like const bool Reverse = false
.
Yes use default argument for bool parameter. For example std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse = false);
Then there is no need of 2nd function
精彩评论