原文:http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Function_Overloading

C++允許function overloading(C語言不允許),可以讓多個functions擁有一樣的名字,只要這些functions的parameters或return type不同。比方說:
class MyClass {
public:
    void Analyze(const string& text);
    void Analyze(const char* text, size_t textlen);
};

Google C++ Style Guide規定,當你要使用function overloading時,必須先確定將來maintain這份code的人可以一眼就看出要使用哪個overload function。如果不能一眼看出的話,那就不要用function overloading。(例如:用AppendString和AppendInteger來取代Append)

Function overloading的好處在於可以解決函數命名的問題(若functions的功能相同,卻因傳入的parameters有些微的差異,就要另外想一個新的function name)。function overloading是template的基礎;function overloading也是visitor pattern所必須。

但function overloading的壞處在於,會讓maintain這份程式的人混淆到底要呼叫哪一個function。若在class繼承時,derived class沒有override base class全部的overload functions,也會讓人感到困惑。

arrow
arrow
    文章標籤
    C++
    全站熱搜

    coherence 發表在 痞客邦 留言(0) 人氣()