c++实践参考:两个成员的类模板(二)

来源:互联网 发布:mit sloan商学院 知乎 编辑:程序博客网 时间:2024/05/17 18:40
/* *Copyright(c)2016.烟台大学计算机学院 *All right reserved. *文件名称:test.cpp *作者:黄金婵 *完成日期:2016年6月20日 *版本号:v1.0 * *问题描述: 请为该类增默认构造函数、带两个参数分别对应两个数据成员初值的构造函数,以及复制构造函数。 *程序输入: *程序输出: */#include <iostream>#include <string>using namespace std;template <class T1,class T2>class Test{public:    Test();    Test(T1 d1, T2 d2);    template <class U,class V> Test(const Test<U,V> &t);    void SetData1(T1 val)    {        data1=val;    }    void SetData2(T2 val)    {        data2=val;    }    T1 GetData1()    {        return data1;    }    T2 GetData2()    {        return data2;    }private:    T1 data1;    T2 data2;};template <class T1,class T2>Test<T1,T2>::Test() {}template <class T1,class T2>Test<T1, T2>::Test(T1 d1, T2 d2):    data1(d1),data2(d2) {}template <class T1,class T2> template <class U,class V>Test<T1, T2>::Test(const Test<U,V> &t):    data1(t.data1),data2(t.data2) {};int main(){    Test <int,double> t1(10, 5.4);    cout<<t1.GetData1()<<"   "<<t1.GetData2()<<endl;    Test <int,double> t2(t1);    cout<<t2.GetData1()<<"   "<<t2.GetData2()<<endl;    return 0;}



知识点总结:

       和使用类一样,使用类模板时要注意其作用域,只能在其有效作用域内用它定义对象。
       模板可以有层次,一个类模板可以作为基类,派生出派生模板类。



0 0
原创粉丝点击