C++面向对象的三大特征——多态(静态多态)

xiaoxiao2021-02-28  67

1     #include <iostream>  2     using namespace std;  3   4     //宏多态;a,b可以不同类型  5     #define  sum(a,b)  ((a) + (b))  6   7     class Base  8     {  9         public: 10             void Print() //不需要定义为虚函数 11             { 12                cout << "base Print() functions" << endl; 13             } 14             void Print(int val) //重载,根据参数列表不同实现函数多态 15             { 16                 cout << "base Print(int) functions" << endl; 17             } 18     }; 19  20     class child : public Base 21     { 22         public: 23             void Print() //不需要定义为虚函数 24             { 25                 cout << "child Print() functions" << endl; 26             } 27             void Print(int val) //重载,根据参数列表不同实现函数多态 28             { 29                 cout << "child Print(int) functions" << endl; 30             } 31              32     }; 33  34     template<typename T> 35     void func(T &p) 36     { 37        p.Print(); 38        p.Print(1); 39     } 40  41     int main() 42     { 43         Base base ; 44         child ch; 45         int a = 23, b = 19; 46         double fa = 13.32, fb = 29.36; 47         func(base); 48         func(ch); 49  50         cout << sum(a,b) << endl; 51         cout << sum(fa,fb) << endl; 52         return 0; 53     }
转载请注明原文地址: https://www.6miu.com/read-68187.html

最新回复(0)