云里雾里的重载,覆盖和隐藏
来源:互联网 发布:淘宝管控记录是什么 编辑:程序博客网 时间:2024/05/16 13:52
重载、覆盖和隐藏的区别:
1.重载发生在同一个类中,函数名相同;覆盖和隐藏发生在有继承关系的两个类中。
2.覆盖和隐藏的区别:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual
关键字,基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,并且参数也相同,但是基类函数没有virtual
关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)。
在实际应用中应避免出现隐藏。
应用区别:
覆盖:行为完全取决于对象类型的
隐藏:行为取决于类型的指针
实例:
#include <iostream.h>
class Base
{
public:
virtual void f(float x){ cout << "Base::f(float) " << x << endl; }
void g(float x){ cout << "Base::g(float) " << x << endl; }
void h(float x){ cout << "Base::h(float) " << x << endl; }
};
class Derived : public Base
{
public:
virtual void f(float x){ cout << "Derived::f(float) " << x << endl; }
void g(int x){ cout << "Derived::g(int) " << x << endl; }
void h(float x){ cout << "Derived::h(float) " << x << endl; }
};
void main(void)
{
Derived d;
Base *pb = &d;
Derived *pd = &d;
// Good : behavior depends solely on type of the object
pb->f(3.14f); // Derived::f(float) 3.14
pd->f(3.14f); // Derived::f(float) 3.14
// Bad : behavior depends on type of the pointer
pb->g(3.14f); // Base::g(float) 3.14
pd->g(3.14f); // Derived::g(int) 3 (surprise!)
// Bad : behavior depends on type of the pointer
pb->h(3.14f); // Base::h(float) 3.14 (surprise!)
pd->h(3.14f); // Derived::h(float) 3.14
}
- 云里雾里的重载,覆盖和隐藏
- 隐藏 重载和覆盖
- 重载,覆盖和隐藏
- 重载、覆盖和隐藏
- 重载、覆盖和隐藏
- 隐藏、覆盖和重载
- 重载、覆盖和隐藏
- 重载、覆盖和隐藏
- 关于C++的覆盖、重载和隐藏
- java方法的重载、覆盖和隐藏
- C++重载、覆盖和隐藏的区别
- 重载,覆盖和隐藏的区别
- C++覆盖、重载和隐藏的区别
- 函数的重载、覆盖和隐藏
- 类的覆盖、重载和隐藏
- 函数的重载、覆盖和隐藏
- 成员函数的重载覆盖和隐藏
- 重载、覆盖和隐藏的区别
- PDF添加书签
- 中国移动开发者社区 的账号和地址
- LibGdx--在LibGdx中使用Toast
- Sicily 1135 飞越原野 (SOJ 1135) 【BFS 广度优先搜索】
- JavaScript 如何给js 空对象动态添加未知属性和值?
- 云里雾里的重载,覆盖和隐藏
- 配置tomcat项目访问路径
- (通过客服端传数据)spring设置动态定时任务
- 马尔可夫模型(Markov models)
- 动态规划---->可靠性设计
- hdu2026首字母变大写
- 移动消息应用迅速崛起 Facebook已经过时了?
- Netty EventLoop与EventExecutor分析(1)
- 第四部分 个人理财风险防范10.当心新的金融诈骗:金蝉脱壳