首页 > 代码库 > 对比C++与Java中的函数重载、覆盖、和隐藏

对比C++与Java中的函数重载、覆盖、和隐藏

                                                     在C++中

1.函数的重载

  C++中的函数的重载要求的是  函数名相同 参数列表必须不同  返回值类型可以相同也可以不相同;只有参数列表不相同,在函数调用时,编译环境才能准确抉择调用的是哪个函数。例如:void display();void display(int  i);void dispaly(double  i);void  display(int i,double i);

void display(double  i,int  i);这几个函数相互构成重载;如果只有返回值类型不同,则是不正确的重载例如:int display();与void display();是不正确的重载;

  另外,C++的函数的重载只能发生在同一级的类中;基类和派生类之间同名函数不能构成重载

2.函数的隐藏

  C++中的函数的隐藏是指基类和派生类之间的同名函数之间,由派生类的函数隐藏掉基类的函数;如果基类的函数与派生类的函数名相同,二参数列表不相同,则基类的函数同样被隐藏,若要调用则必须指明作用域::

 

 1 #include<iostream> 2 using namespace std; 3 class person 4 { 5   public : 6       void display(int i){cout<<"基类被调用"<<endl;} 7       //int display(int i){return 0;} 8 }; 9 class student:public person10 {11    public :void display(){cout<<"派生类被调用"<<endl;}12 };13 int main()14 {15     student *stu=new student();16     //stu->display(0);//错误:C++中函数的重载只能在同一个类中同时也不能发生覆盖17     //stu->person::display(0);//可以这样写18     stu->display();//输出 派生类被调用

    /* person *per=new student();
      per->display();//输出基类被调用//这是与覆盖的区别所在
*/
19 return 0;20 }

3.函数的覆盖

  C++中函数覆盖的条件是:

  (1)基类的函数必须是虚函数

  (2)发生覆盖的两个函数要位于派生类和基类中

  (3)函数名与参数列表必须完全相同

#include<iostream>using namespace std;class person{public :    virtual void display(){cout<<"基类函数被调用"<<endl;};};class student:public person{public :    void display(){cout<<"派生类函数被调用"<<endl;}};int main(){    person *per=new person();    per->display();//输出基类被调用    delete per;    per=new student();    per->display();//输出派生类函数被调用//这一点是覆盖与隐藏的区别    return 0;}

                                在Java中

1  函数的重载

   在Java中函数的重载 可以发生在基类和派生类之间 同样要求函数名相同函数,参数列表不同,返回值类型可以相同可以不相同

 1 class BaseClass  2 { 3     public static void display(int i){System.out.println("Baseclass");} 4 } 5 public class ThisClass extends BaseClass 6 { 7     public static void display(){System.out.println("ThisClass");} 8     public static void main(String[]args) 9     {10         display();//调用派生类的函数11         display(0);//调用基类的函数
      ////////////////////////////////////////////////////////////
      此处并没有发生覆盖和隐藏 与C++不同
12 }13 }

 

    此例中基类BaseClass 中的void display(int i);与派生类ThisClass中的void display();构成了重载

2.函数的覆盖

  Java中函数的覆盖要求基类与派生类的 函数名、参数列表完全相同。示例如下:

 

 1 public class PrivateOverride 2 { 3     public  void f(){System.out.println("private f()");} 4     //private void f(){System.out.println("private f()");} 5     public static void main(String[]args) 6     { 7         PrivateOverride po=new Derived(); 8         po.f();//输出public f()//表明派生类函数覆盖了基类的函数 9     }10     11 }12 class Derived extends PrivateOverride13 {14         public void f(){System.out.print("public f()");}15 }

 

3.上例中 如果把基类中 f()的访问属性置为private,则输出 private f()   得出的结论是只有非private方法才可以被覆盖

 

对比C++与Java中的函数重载、覆盖、和隐藏