一 : 继承模板:
#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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。