【Java與C++之間的一些差異】之 方法重載

來源:互聯網
上載者:User

相同點:

都是在同一類裡的一些同名,不同參數的方法形成重載。

都會出現參數傳遞時類型匹配的二義性匹配問題:

add(1,2) ;public void add(double a, float b) {...}public void add(float a, double b) {...}


不同點:

對於C++來說重載還可以發生在相同參數的const與非const版本之間,但是java不行對於java來說相同參數的final和非final版本函數不會構成重載。(編譯器會報錯)

public void xx1(int a) { ... } public void xx1(final int c) { ... } /* these are not overload methods, the xx1 is repeaed defined */ 

對於可變參數

public void test (String msg) {...}public void test (String... msgs) {...}obj.test("Tom") ; /* there call the firest test *//* follow call the second test */obj.test("Evan, Tank) ;obj.test() ; 

可以看出只有與非可變參數的方法完全符合才會調用此方法,否則都會調用可變參數的。

可變參數方法重載引出的二義性問題

public void go(int ... nums) {...}              /* at least has 0 parameter */public void go(int a, int... nums) {...}          /* at least has 1 parameter */public void go(int a, int b, int... nums) {...}   /* at least has 2 parameters */ obj.go(1) ;     /* can be called by firest and second method */ obj.go(1,2);    /* can be called by 1st,2nd,3th methods */obj.go(1,2,3) ; /* can be called by 1st, 2nd, 3th methods */


上面的3個go來說它們的區別在於對最小參數個數的限制,如果一個調用他傳遞的參數的個數>=兩個以上的重載函數,那麼對於這個調用來說滿足他的參數的重載方法都是他的首選,從而可能出現二義性問題。如上面的obj.go(1) 對於他來說第一個和第二個方法均是首選從而導致編譯時間的二義性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.