2010-12-17 85 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);然後不需要第二個功能