您好,登錄后才能下訂單哦!
一 : 繼承模板:
#include <iostream> using namespace std; template<typename T = char>//如果是類模板,是可以加默認值的 T = char class CPeople { public: T a; CPeople(T a) { this->a = a; } void print() { cout << "CPeople a =" << a << endl; } }; template<typename T , typename Y> class CAonaufly : public CPeople<Y> { public: T c; CAonaufly( T c , Y y ):CPeople<Y>(y)// == CAonaufly( T c , Y y ):CPeople(y) { this->c = c; } void show() { cout << "CAonaufly c=" << c << endl; } }; int main() { CAonaufly<int , char> ca( 12 , 'k'); ca.print(); ca.show(); return 0; }
結果:
解析:
① 在子類的構造函數中 , 如何調用父類的構造函數 CAonaufly( T c , Y y ):CPeople<Y>(y)// == CAonaufly( T c , Y y ):CPeople(y) 這2種都是可以的。
② 子類也可以不用模板 , 這樣就把子類給寫死了例如CKayer , 直接寫死了父類T為char類型:
#include <iostream> using namespace std; template<typename T = char>//如果是類模板,是可以加默認值的 T = char class CPeople { public: T a; CPeople(T a) { this->a = a; } void print() { cout << "CPeople a =" << a << endl; } }; template<typename T , typename Y> class CAonaufly : public CPeople<Y> { public: T c; CAonaufly( T c , Y y ):CPeople<Y>(y)// == CAonaufly( T c , Y y ):CPeople(y) { this->c = c; } void show() { cout << "CAonaufly c=" << c << endl; } }; class CKayer : public CPeople<char> { public: CKayer( char c ) : CPeople(c) { } }; int main() { system("color 1A"); CAonaufly<int , char> ca( 12 , 'k'); ca.print(); ca.show(); cout << "======================================" << endl; CKayer ck('q'); ck.print(); return 0; }
二 : 多態模板
#include <iostream> using namespace std; template<typename T = char>//如果是類模板,是可以加默認值的 T = char class CPeople { public: T a; CPeople(T a) { this->a = a; } void print() { cout << "CPeople a =" << a << endl; } }; template<typename T , typename Y> class CAonaufly : public CPeople<Y> { public: T c; CAonaufly( T c , Y y ):CPeople<Y>(y)// == CAonaufly( T c , Y y ):CPeople(y) { this->c = c; } void show() { cout << "CAonaufly c=" << c << endl; } }; class CKayer : public CPeople<char> { public: CKayer( char c ) : CPeople(c) { } }; int main() { system("color 1A"); CPeople<char> * ca = new CAonaufly<int , char>(12 , 'k'); ca->print(); delete ca; return 0; }
結果:
解析:
①
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。