对比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;
}
相关推荐
![](/images/ad-banner/ad-banner.png)
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11