码迷,mamicode.com
首页 > 其他好文 > 详细

类成员函数的 重载、覆盖和隐藏区别

时间:2014-08-27 18:13:48      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   2014   art   

重载:
成员函数被重载的特征:
(1)相同的范围(在同一个类中);
(2)函数名字相同;
(3)参数不同;
(4)virtual 关键字可有可无。

bubuko.com,布布扣
 1 #include <iostream>
 2 
 3 using std::cin;
 4 using std::cout;
 5 using std::endl;
 6 
 7 class A
 8 {
 9 public:
10     void show(int val) { cout << val; }
11     void show(double val) { cout << val; }
12 };
13 
14 int main(void)
15 {
16     A a;
17     a.show(4);
18     cout << endl;
19     a.show(4.2);
20     cin.get();
21 }
View Code

 

覆盖:
覆盖是指派生类函数覆盖基类函数,特征是:
(1)不同的范围(分别位于派生类与基类);
(2)函数名字相同;
(3)参数相同;
(4)基类函数必须有virtual 关键字。

bubuko.com,布布扣
 1 #include <iostream>
 2 
 3 using std::cin;
 4 using std::cout;
 5 using std::endl;
 6 
 7 class A
 8 {
 9 public:
10     virtual void show(int val) { cout << val; }
11 };
12 
13 class B : public A
14 {
15 public:
16     void show(int val) { cout << "--" << val << "--"; }
17 };
18 
19 int main(void)
20 {
21     A a;
22     a.show(4);
23     cout << endl;
24 
25     A* p = new B;
26     p->show(5);
27 
28     cin.get();
29 }
View Code

bubuko.com,布布扣

 

隐藏:
隐藏是指派生类的函数屏蔽了与其同名的基类函数,规则如下:
(1)如果派生类的函数与基类的函数同名,但是参数不同。此时,不论有无virtual关键字,基类的函数将被隐藏(注意别与重载混淆)。
(2)如果派生类的函数与基类的函数同名,且参数也相同,但基类函数没有virtual 关键字。此时,基类的函数被隐藏(注意别与覆盖混淆)

 

注:小生看到别人的文档,遂加代码记录下来。不要告我啊!我没钱,O(∩_∩)O哈哈~

类成员函数的 重载、覆盖和隐藏区别

标签:style   blog   http   color   os   io   ar   2014   art   

原文地址:http://www.cnblogs.com/jiayith/p/3939683.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!