重写 重载 隐藏
2016-04-10 11:30
302 查看
C++中有很多概念,很容易混淆,下面主要来说一下重载,重写和隐藏的区别:
重载:overload --函数名一样,函数的参数不同(包括参数的个数,参数的类型),返回值没有要求:
重写:override --函数名称,参数,返回值一样(返回值仅限父类和子类的时候不一样);
隐藏:hide--重载的函数放在子类和父类中就会形成隐藏:
#include <iostream>
using namespace std;
void aa(int a ) //函数的重载,函数名称相同,函数参数不一样,根据参数的个数来调用函数;
{
cout<<"aa"<<endl;
}
void aa(int a,int b)
{
cout<<a<<b<<endl;
}
class father
{
public:
void show()
{
cout<<"this is the father"<<endl;
}
void cc()
{
cout<<"this is the father cc"<<endl;
}
};
class son :public father
{
public:
void show() //重写父类的show函数;名称参数一样,功能不一样;
{
cout<<"this is the son show"<<endl;
}
void cc(int a ,int b) //隐藏不能根据函数的参数来调用函数,只能用对象或者类名+::作用域来调用;
{ //把father中的cc隐藏了;
cout<<"this is the son cc"<<endl;
}
};
int main()
{
son s;
s.father::cc(); //类名+ ::来调用隐藏的函数;
s.cc(100,200);
s.show();
s.father::show();
system("pause");
return 0;
}
重载只是一种语言特性,与多态无关,因为它是在编译期间就进行了函数的绑定,也就是静态绑定,属于早绑定!早绑定与静态绑定与多态和面向对象无关!
如
void fun(int a);
void fun(int a, char *b);
经过编译后,在编译期间可能处理为:i_fun()和char_fun(),这样的标示和绑定!!
重载:overload --函数名一样,函数的参数不同(包括参数的个数,参数的类型),返回值没有要求:
重写:override --函数名称,参数,返回值一样(返回值仅限父类和子类的时候不一样);
隐藏:hide--重载的函数放在子类和父类中就会形成隐藏:
#include <iostream>
using namespace std;
void aa(int a ) //函数的重载,函数名称相同,函数参数不一样,根据参数的个数来调用函数;
{
cout<<"aa"<<endl;
}
void aa(int a,int b)
{
cout<<a<<b<<endl;
}
class father
{
public:
void show()
{
cout<<"this is the father"<<endl;
}
void cc()
{
cout<<"this is the father cc"<<endl;
}
};
class son :public father
{
public:
void show() //重写父类的show函数;名称参数一样,功能不一样;
{
cout<<"this is the son show"<<endl;
}
void cc(int a ,int b) //隐藏不能根据函数的参数来调用函数,只能用对象或者类名+::作用域来调用;
{ //把father中的cc隐藏了;
cout<<"this is the son cc"<<endl;
}
};
int main()
{
son s;
s.father::cc(); //类名+ ::来调用隐藏的函数;
s.cc(100,200);
s.show();
s.father::show();
system("pause");
return 0;
}
重载只是一种语言特性,与多态无关,因为它是在编译期间就进行了函数的绑定,也就是静态绑定,属于早绑定!早绑定与静态绑定与多态和面向对象无关!
如
void fun(int a);
void fun(int a, char *b);
经过编译后,在编译期间可能处理为:i_fun()和char_fun(),这样的标示和绑定!!
相关文章推荐
- 共同学习Java源码--常用数据类型--String(十三)
- Stanford ex1: Linear Regression
- 正则表达式
- 框架设计
- vim常用技巧
- [Hihocoder 1289] 403 Forbidden (微软2016校园招聘4月在线笔试)
- http2
- VMware Workstation装Mac OS X出现无法恢复错误vcpu-0
- 关于javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional
- 混合专家系统(Mixture of experts)
- leetcode之Binary Tree Level Order Traverse
- 来自谷歌的MVP的示例
- __attribute__((regparm(n)))
- hellocharts_柱状图
- 互联网--评微软等公司数据结构和算法面试100题 .
- 全球最低功耗蓝牙单芯片DA14580的软件体系 -RW内核和消息处理机制
- 互联网--评微软等公司数据结构和算法面试100题 .
- Example016实现下拉框
- Longest Valid Parentheses
- Android开发工具: AS, Gradle, Git等