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

类继承中默认参数值问题

时间:2016-09-08 23:23:11      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:

技术分享
 1 #include<iostream>
 2 #include<ctime>
 3 #include <stdio.h>
 4 #include<cstring>
 5 #include<cstdlib>
 6 #include <map>
 7 #include <string>
 8 using namespace std;
 9 class A
10 {
11 public:
12     A(){
13         cout << "A()" << endl;
14     }
15 
16     ~A(){
17         cout << "~A()" << endl;
18     }
19     virtual void func(int val = 1)
20     {
21         std::cout << "A->" << val << std::endl;
22     }
23 
24     virtual void test()
25     {
26         func();
27     }
28 };
29 
30 class B:public A
31 {
32 public:
33     B(){
34         cout << "B()" << endl;
35     }
36 
37     ~B(){
38         cout << "~B()" << endl;
39     }
40     void func(int val = 0)
41     {
42         std::cout << "B->" << val << std::endl;
43     }
44 };
45 
46 #if 1
47 int main(){
48     B*p = new B;
49     p->test();
50     delete p;
51 }
52 #endif
View Code

由于p指向了继承类B的对象,所以,在调用A中的test之后,虚函数func()会调用继承类B的函数,而默认形参仍然会使用test所在的类A的形参1,从而输出B->1。

类继承中默认参数值问题

标签:

原文地址:http://www.cnblogs.com/guxuanqing/p/5854724.html

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