Function overloading — two functions only differ by a default parameter

前端 未结 7 2111
有刺的猬
有刺的猬 2020-12-06 07:21
class A{
    public:
        void foo(int x)
        {
            cout << \"foo with one\\n\";
        }

        void foo(int x, int y=10)
        {
                 


        
7条回答
  •  醉酒成梦
    2020-12-06 08:05

    The ambiguity doesn't happen because of optional parameters but only happens when you have the same kind of prototype with same optionals but different names.. thats what I figured out..

    I actually thought i got lucky when my example similar to yours worked.. but when I put 2 different prototype names with same optional parameters then it started complaining about ambiguities

    This below gives the ambiguity error

    void UpdateTextColor(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color);
    void CreateColoredText(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color);
    
    void UpdateTextColor(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color = FALSE)
    {
       //...
    }
    
    void CreateColoredText(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color = FALSE)
    {
       //...
    }
    

    But this doesn't and note I am still using a optional parameter

    void UpdateTextColor(HWND hwndControl, DWORD text_color, DWORD back_color);
    void CreateColoredText(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color);
    
    void UpdateTextColor(HWND hwndControl, DWORD text_color, DWORD back_color)
    {
       //...
    }
    
    void CreateColoredText(HWND hwndControl, DWORD text_color, DWORD back_color, BOOL control_back_color = FALSE)
    {
       //...
    }
    
    //My call is like this (note only 3 params used out of 4)
    
    CreateColoredText(GetDlgItem(hDlg, BLAHBLAH), RGB(0, 0, 0), RGB(127, 127, 127));
    

提交回复
热议问题