简单理解:同一个接口,多种实现方式,让不同类的的对象对同一件事情可以采用不同方法去做
1.2 多态的作用(1)应用程序可以不必为一个派生类编写功能调用,而只需要对抽象基类进行处理即可,实现代码重用;
(2)派生类的功能可以被基类的方法或引用变量调用,这称作向后兼容。
动态分为动态多态,静态多态,函数多态和宏多态,编程者的动态多态通常是指动态多态,是是基于继承机制和虚函数实现的。
2.1动态的实例(1)用指针来来实现多态:
#includeusing namespace std; class base { public: virtual void test() { cout<<"this is base"< test(); base* base_q = new derived_two; base_q->test(); return 0; }
(2)用引用实现动态多态
#includeusing namespace std; class base { public: virtual void test() { cout<<"this is base"< 2.2静态多态(用模板)的实现
#includeusing namespace std; class base { public: virtual void test() { cout<<"this is base"< void all_test( base_or_derived &obj) { obj.test(); } int main() { base base_self; all_test(base_self); derived_one one; all_test(one); derived_two two; all_test(two); return 0; } 2.3函数多态(重载)实例
#include#include using namespace std; int my_add(int a, int b) { return a + b; } int my_add(int a, string b) { return a + atoi(b.c_str()); } int main(void) { int i = my_add(1, 2); int s = my_add(1, "2"); cout << "i = " << i << endl; cout << "s = " << s << endl; return 0; } 2.4 宏多态的实例
#include#include using namespace std; #define ADD(a, b) ((a)+(b)) int main(void) { int i = ADD(2, 3); string s1("hello "), s2("world"); string s = ADD(s1, s2); cout << i << endl; cout << s << endl; return 0; }



