cpp基础部分
模板
函数模板:
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
| template<typename T> void Swap(T &a, T &b){ T temp = a; a = b; b = temp; } -or- #include <iostream> using namespace std; template<typename T> T max(T a, T b, T c); template<typename T> T max(T a, T b, T c){ T max_num = a; if(b > max_num) max_num = b; if(c > max_num) max_num = c; return max_num; } int main( ){ int i1, i2, i3, i_max; cin >> i1 >> i2 >> i3; i_max = max(i1,i2,i3); cout << "i_max=" << i_max << endl; double d1, d2, d3, d_max; cin >> d1 >> d2 >> d3; d_max = max(d1,d2,d3); cout << "d_max=" << d_max << endl; long g1, g2, g3, g_max; cin >> g1 >> g2 >> g3; g_max = max(g1,g2,g3); cout << "g_max=" << g_max << endl; return 0; }
|
类模板:
1 2 3
| template<typename 类型参数1 , typename 类型参数2 , …> class 类名{ };
|
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
| #include <iostream> using namespace std; template<class T1, class T2> //这里不能有分号 class Point{ public: Point(T1 x, T2 y): m_x(x), m_y(y){ } public: T1 getX() const; void setX(T1 x); T2 getY() const; void setY(T2 y); private: T1 m_x; T2 m_y; }; template<class T1, class T2> //模板头 T1 Point<T1, T2>::getX() const { return m_x; } template<class T1, class T2> void Point<T1, T2>::setX(T1 x){ m_x = x; } template<class T1, class T2> T2 Point<T1, T2>::getY() const{ return m_y; } template<class T1, class T2> void Point<T1, T2>::setY(T2 y){ m_y = y; } int main(){ Point<int, int> p1(10, 20); cout<<"x="<<p1.getX()<<", y="<<p1.getY()<<endl; Point<int, char*> p2(10, "东经180度"); cout<<"x="<<p2.getX()<<", y="<<p2.getY()<<endl; Point<char*, char*> *p3 = new Point<char*, char*>("东经180度", "北纬210度"); cout<<"x="<<p3->getX()<<", y="<<p3->getY()<<endl; return 0; }
|
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
| #ifndef TEMPLATE_DEMO_HXX #define TEMPLATE_DEMO_HXX template<class T> class A{ public: T g(T a,T b); A(); }; #endif
#include<iostream.h> #include "TemplateDemo.h" template<class T> A<T>::A(){} template<class T> T A<T>::g(T a,T b){ return a+b; } void main(){ A<int> a; cout<<a.g(2,3.2)<<endl; }
|
利用标志位记录状态
注:案例中unsigned char mFlags 八位
存储
1 2 3 4 5 6 7
| ckass Flag{ bool check(参数) const; void set(参数); void reset(参数); private: unsigned char mFlags; }
|
获取
普通计算
2D部分
3D部分
Update