标签:
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
由于p指向了继承类B的对象,所以,在调用A中的test之后,虚函数func()会调用继承类B的函数,而默认形参仍然会使用test所在的类A的形参1,从而输出B->1。
标签:
原文地址:http://www.cnblogs.com/guxuanqing/p/5854724.html