关于C++ , java继承重载

来源:互联网 发布:足球战术板 软件 编辑:程序博客网 时间:2024/05/16 00:45
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)
*/
//:~

原创粉丝点击