C++模板类(泛型类)学习总结

调试了一下午,发现用C++写模板方法真是有不少值得注意的地方,不是一般的麻烦,没点经验总结真是不行的。
首先,写模板类(template class),这个在java叫作泛型类,需要注意几点,在写泛型类时.h头文件和实现(.cpp)不能分离,也就是说,关于泛型类/模板类的所有逻辑都 要写在一个文件中,我的做法是将类的函数体和函数原型都写入头文件,而省去.cpp的implement的文件。
头文件如下:
#ifndef MOTHER_STUDENT_H
#define MOTHER_STUDENT_H
#include "Student.h"
#include <vector>
using namespace Member;
//下面是声名
template<class T>
class MotherStudent:public Student{  //这里是继承了一个父类(学生妈妈类继承学生父类,该父类有个纯虚函数void testVir() const),这个学生妈妈类拥有一个容器vector,装着她生的学生孩子,呵呵)
private:
    vector<T>* children; //成员函数,指针
public:
    MotherStudent(){
        this->children = new vector<T>();
        std::cout << "这个妈妈创建了" << std::endl;
    }
    void setChildren(vector<T>&);
    vector<T>& getChildren();
//该实现父类的纯虚函数
    void testVir(int a) const{
        std::cout  <<a <<std::endl;
    }


};
//类定义体结束,下面是定义
template<class T>
void MotherStudent<T>::setChildren(vector<T>& children){
    this->children = &children;
}
template<class T>
vector<T>& MotherStudent<T>::getChildren(){
    std::cout << "这是来自于实现体的模版方法" << std::endl;
    return *(this->children);
}
#endif

上面将这个模板类的头文件写完了,然后在main程序的文件中写:
int _tmain(int argc, _TCHAR* argv[]){
    MotherStudent<Student*> mother_std_obj;
    MotherStudent<Student*>* mother_std = &mother_std_obj; //请注意这里的写法,不能写MotherStudent<Student>* mother_std = .. 因为C++中如果写Student是抽象类(含纯虚函数),这样会尖括号中直接写类名会用无参构造函数构造这个类的,然后报错:“抽象类不能实例化”,所以这里用指针了。
    vector<Student*> *children = new vector<Student*>();
    for(int i = 0;i<4;i++){ //这个妈妈学生对象的children成员装入四个CollegeStudent对象(该对象也是继承自Student类的,所以可以装入)
        //这是int转换成string的标准方法
        stringstream strm;
        strm<<i;
        string name = "乔布斯" + strm.str()+"号";
        //CollegeStudent构造函数2个参数,age和name
        Student* per = new CollegeStudent(i,name); //因为模板类那里定义成了指针的,所以该模板类的T是Student*指针,所以里面的children成员变量也是包含指针的vector集合。
        children->push_back(per);
    }
   
    mother_std->setChildren(*children); //setChildren方法的形参是定义成“引用”的了,所以这里传入的是“解引用符号"解的指针。
    for(vector<Student*>::iterator iter=mother_std->getChildren().begin();iter!=mother_std->getChildren().end();iter++){
        //iter是得到"指向Student*的指针",所以(*iter)得到Student*,然后->name,访问name
        std::cout << "name is " <<(*iter)->name<< " age is " << (*iter) ->getAge() << std::endl;
    }
}   

最后,展示程序运行结果:

posted @ 2012-01-27 11:10  sharpstill  阅读(6666)  评论(0编辑  收藏  举报