C++ 多态性

编译时多态

函数模板

//例1 函数模板体现编译期多态性
#include <iostream>
using namespace std;


template <typename T>
T add(T a, T b)

{

     t c = a+b;
     return c;

}


int main()

{

     int a1 = 1;
     int b1 = 2;
     int c1 = add(a1,b1);
     cout<<"c1:"<<c1<<endl;

     double a2 = 2.0;
     double b2 = 4.0;
     double c2 = add(a2,b2);
     cout<<"c2:"<<c2<<endl;

}
View Code

 

运行时多态

虚函数

 1 #include <iostream>
 2 using namespace std;
 3  
 4 
 5 class A{
 6 public:
 7      void f1()
 8      {
 9           cout<<"A::f1()"<<endl;
10      }
11      virtual void f2()
12      {
13           cout<<"A::f2()"<<endl;
14      }
15 };
16 
17 
18 class B:public A
19 {
20 public:
21      //覆盖
22      void f1()
23      {
24           cout<<"B::f1()"<<endl;
25      }
26      //重写
27      virtual void f2()
28      {
29           cout<<"B::f2()"<<endl;
30      }
31 };
32 
33 
34 int main()
35 {
36      A* p = new B();
37      B* q = new B();
38      p->f1();          //调用A::f1()
39      p->f2();          //调用B::f2(),体现多态性
40      q->f1();          //调用B::f1()
41      q->f2();          //调用B::f2()
42      return 0;
43 }
View Code

 

纯虚函数

virtual void f() = 0;

 

posted @ 2018-09-27 16:42  yimuxi  阅读(160)  评论(0)    收藏  举报