C++模板Template的使用,精簡詳解,秒懂。
阿新 • • 發佈:2019-01-04
為了能夠完整地描述模板的建立和具體使用,以下會有完善的測試,請大家耐心看下去,基本可以看得懂,即學即用。
// CPP面向物件.cpp: 定義控制檯應用程式的入口點。 // #include "stdafx.h" #include <iostream> using namespace std; template <class T> class MyClass { public: MyClass(T e); ~MyClass(); void printSum(T f); void noPara(T); T mul = 11; T mulSet; T add(); void undefine(); private: T a; T b; T c; T d; protected: }; template<class T> MyClass<T>::MyClass(T e):a(10), b(30), c(90), d(99) { this->d = 666; cout << "Hello World!" << a << " -- " << b << " -- " << c << " -- " << d << " -- " << e << endl; } template<class T> MyClass<T>::~MyClass() { return; } template<class T> void MyClass<T>::printSum(T f) { cout << a + b + c + d + f << endl; } template<class T> void MyClass<T>::noPara(T adc) { cout << "I am adc(" << adc << ")" << endl; } template<class T> T MyClass<T>::add() { return ((this->a + this->b + this->c + this->d) * this->mul) * this->mulSet;; } template<class A, class B> class MyClass2 { public: MyClass2(A intA, B charB, B *intBs); ~MyClass2(); B ch1; B ch2[10]; private: }; template<class A, class B> MyClass2<A, B>::MyClass2(A intA, B intB, B *intBs) : ch1('c'), ch2("ch2") { cout << "A intA:" << intA << " -- " << "B intB:" << intB << "B intBs:" << intBs << " -- " << "ch1 = " << ch1 << " -- " << "ch2 = " << this->ch2 << endl; } template<class A, class B> MyClass2<A, B>::~MyClass2() { return; } template<class V> class MyClass3 { public: MyClass3(); ~MyClass3(); V test(); private: }; template<class V> MyClass3<V>::MyClass3() { } template<class V> MyClass3<V>::~MyClass3() { } template<class V> V MyClass3<V>::test() { cout << "test" << endl; } template<class V, class C> V vcFoo(C c) { cout << "V and C = " << c << endl; } int main() { MyClass<int> mc(55); mc.printSum(88); mc.mulSet = 123; cout << mc.add() / 123 << endl; mc.noPara(99); char NCAA[10] = "NCAA"; MyClass2<int, char> mc2(2, 'BBC', NCAA); //'BBC'取最後一個字元'C' MyClass3<void> ss; ss.test(); vcFoo<void>(10); system("pause"); return 0; }