对比C++与Java中的函数重载、覆盖、和隐藏
作者:网络转载 发布时间:[ 2014/11/25 13:05:00 ] 推荐标签:Java C++ 函数重载
在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 person
10 {
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;
}

sales@spasvo.com