原创文章,转载请注明出处,谢谢!
作者:清林,博客名:飞空静渡
我们有这么一组这样的类,其类继承关系如下图:
我们先把base, man, 和woman的类写出来,test.h文件
#ifndef TEST_H #define TEST_H #include <iostream> using namespace std; class base { public: base (int id, bool bman):id_(id), bMan(bman){cout<<"base function!"<<endl;} virtual ~base (){} bool sexMan() { return bMan;} protected: int id_; bool bMan; // false is woman, true :is man }; class man :public base { public: man (int id):base(id, true){cout<<"I'am a man, id is "<<id_<<endl;} protected: }; class woman : public base { public: woman (int id): base(id, false){cout<<"I'am a woman, id is "<<id_<<endl;} protected: }; #endif
如果我们要写一个男教师的类manTeacher的话就得从man上继承,同理womanTeacher就得从woman上继承,这样我们就得写下两个类了,但这里我们可以通过模板来简化类的写,如下(在test.h文件下面添加):
template<class T> class teacher : public T { public: teacher(int id):T(id){} void say() { if (sexMan()) cout<<"I'am a man teacher!"<<endl; else cout<<"I'am a woman teacher!"<<endl; } private: /* data */ };
我们测试一下,新建一个cpp文件,main.cpp
#include <vector> #include "test.h" int main(int argc, char *argv[]) { teacher<man> t1(5); t1.say(); }
在vc上可以直接编译,在g++上,要添加-fpermissive,添加这个可以让模板代码由出错降为警告,从而编译通过,vc可以直接编译通过。
编译:
g++ -g -Wall -fpermissive main.cpp
运行: ./a.out
base function!
I'am a man, id is 5
I'am a man teacher!
我们再次修改如下:
#include <vector> #include "test.h" int main(int argc, char *argv[]) { base* b = new teacher<man>(3); teacher<man> *t = (teacher<man> *)b; t->say(); return 0; }
编译输出:./a.out
base function!
I'am a man, id is 3
I'am a man teacher
再次修改main.cpp
#include <vector> #include "test.h" int main(int argc, char *argv[]) { std::vector<base*> vb; base* b1 = new teacher<man>(3); base* b2 = new teacher<woman>(5); vb.push_back(b1); vb.push_back(b2); for(std::vector<base*>::iterator it = vb.begin(); it != vb.end(); ++it) { if ((*it)->sexMan()) { teacher<man> *t = (teacher<man> *) (*it); t->say(); } else { teacher<woman> *t = (teacher<woman> *) (*it); t->say(); } } return 0; }
编译输出:./a.out
base function!
I'am a man, id is 3
base function!
I'am a woman, id is 5
I'am a man teacher!
I'am a woman teacher!