關於C++ , java繼承重載

C++ 重載只能是同一個類中,
子類重載的話,父類裏面的同名方法就被隱藏掉了,即使參數不同
用限定符 :: 可以找到~

#include<iostream>
using namespace std;

class Base {
public:
    
void foo (int i) {
        cout
<<"Base foo int "<<i<<endl;;
    }

    
void foo () {
        cout
<<"Base foo none "<<endl;
    }

}
;

class Drived: public Base {
public:
    
void foo (float f) {
        cout
<<"Drived foo float "<<f<<endl;
    }

}
;

int main()
{
    Drived  derive;     
    derive.foo(
6.9f);  // Output: Drived foo float 6.9
    
//!  obj.foo();       Error
    
//!  derive.foo(2);   Error
    derive.Base::foo();  // OK, Output: Base foo none
    derive.Base::foo(2); //             Base foo int 2
    return 0;
}

而Java允許導出類重新定義父類方法而不會屏蔽其在基類的任何版本
//: reusing/Hide.java
// Overloading a base-class method name in a derived
// class does not hide the base-class versions.

class Homer {
  
char doh(char c) {
    System.out.println(
"doh(char)");
    
return 'd';
  }

  
float doh(float f) {
    System.out.println(
"doh(float)");
    
return 1.0f;
  }

}


class Milhouse {}

class Bart extends Homer {
  
void doh(Milhouse m) {
    System.out.println(
"doh(Milhouse)");
  }

}


public class Hide {
  
public static void main(String[] args) {
    Bart b 
= new Bart();
    b.doh(
1);
    b.doh(
'x');
    b.doh(
1.0f);
    b.doh(
new Milhouse());
  }

}
 /* Output:
doh(float)
doh(char)
doh(float)
doh(Milhouse)
*/
//:~

width="728" scrolling="no" height="90" frameborder="0" align="middle" src="http://download1.csdn.net/down3/20070601/01184120111.htm" marginheight="0" marginwidth="0">
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章