1. 面向对象编程的奥义在于每种数据都自带其操作,这样使用者就不必了解如何操作复杂的数据结构了,而只需要学习这种数据的接口即可;
2.泛型编程使得编写的一种算法可以广泛用于各种类型的数据,这样就不必为每种类型的数据重新重载一次函数。
逻辑自洽。
1. 面向对象编程的奥义在于每种数据都自带其操作,这样使用者就不必了解如何操作复杂的数据结构了,而只需要学习这种数据的接口即可;
2.泛型编程使得编写的一种算法可以广泛用于各种类型的数据,这样就不必为每种类型的数据重新重载一次函数。
“泛型编程旨在编写独立于数据类型的代码” 《c++ primer plus》(6th ed)
实现一种方法,可以用于各种类型的数据。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include<iostream> using namespace std; template <class Nott> class Stack{ private: Nott arr[20]; int num; public: Stack(); void push(const Nott& ele); void print(); }; template <class Nott> Stack<Nott>::Stack(){ num = 0; } template <class Nott> void Stack<Nott>::push(const Nott& ele){ arr[num] = ele; num ++; } template <class Nott> void Stack<Nott>::print(){ for(int i = 0;i < num;i ++) cout << arr[i] << " "; cout << endl; } int main(){ Stack<char> nott; nott.push('N'); nott.push('O'); nott.push('T'); nott.push('T'); nott.print(); Stack<int> nottt; nottt.push(6); nottt.push(6); nottt.push(6); nottt.push(6); nottt.print(); return 0; } |
输出结果:
1 2 |
I C B C 6 6 6 6 |