标签:
代码:
1 #include <iostream> 2 #include <cstring> 3 4 using namespace std; 5 6 class Base{ 7 public: 8 virtual void func1(); 9 virtual void func2(); 10 void func3(); 11 void func4(); 12 }; 13 14 void Base::func1(){ 15 cout<<"Base func1"<<endl; 16 } 17 18 void Base::func2(){ 19 cout<<"Base func2"<<endl; 20 } 21 22 void Base::func3(){ 23 cout<<"Base func3"<<endl; 24 } 25 26 void Base::func4(){ 27 cout<<"Base func4"<<endl; 28 } 29 30 class Derived1:public Base{ 31 public: 32 void func1();//virtual可以省略 33 //char func2(){};错误,虚函数返回类型需要一致 34 void func3(); 35 char func4(); 36 }; 37 38 void Derived1::func1(){ 39 cout<<"Derived1 func1"<<endl; 40 } 41 42 void Derived1::func3(){ 43 cout<<"Derived1 func3"<<endl; 44 } 45 46 char Derived1::func4(){ 47 cout<<"Derived1 func4 can change the return type"<<endl; 48 } 49 50 class Derived2:public Base{ 51 public: 52 void func1(); 53 }; 54 55 void Derived2::func1(){ 56 cout<<"Derived2 func1"<<endl; 57 } 58 59 int main(){ 60 61 Base *B; 62 Derived1 De1; 63 B = &De1; 64 B->func1(); 65 B->func3(); 66 B->func4(); 67 De1.func4(); 68 69 Derived2 *pDe2; 70 pDe2 = (Derived2*)&De1; 71 pDe2->func1(); 72 73 return 0; 74 75 }
输出:
Derived1 func1 Base func3 Base func4 Derived1 func4 can change the return type Derived1 func1
总结:
1、虚函数必须在父类中必须实现,不实现可以用纯虚函数;
2、子类虚函数的返回类型必须与父类中的返回类型一致,普通函数则可以不同;
3、子类虚函数如果参数发生变化,则虚特性消失。
标签:
原文地址:http://www.cnblogs.com/hu983/p/5408658.html