[C++] 模板编程-07 类模板继承

一 分类

  • 普通类继承模板类
  • 类模板继承普通类
  • 类模板继承类模板
  • 类模板继承模板类
  • 类模板继承类型参数

二 普通类继承模板类

  • 首先我们创建一个类模板(只有有了类模板才能创建出模板类)
  • 对于在子类中是否要构造父类,我们有三种处理方式
  • 第一种:我们在父类构造函数中指定构造的默认值比如qt中的QWidget *parent = nullptr这样在子类的构造函数中就不需要显示构造父类了
  • 第二种:在子类构造函数的初始化列表中显示构造父类的构造函数,并且同时在子类的构造函数参数中传入父类构造需要的类型。
  • 第三种:在子类构造函数的初始化列表中显示构造父类的构造函数,直接在初始化列表中给出默认值,不需要在子类的构造函数中显式的传入。
template <typename T1>
class templateA
{
private:
    T1 m_a;
public:
    templateA(T1 a):m_a(a){}
    void debug()
    {
        qDebug()<<"templateA = "<<m_a;
    }

};

  • 然后创建一个普通类在继承时实例化模板类
  • 这里要注意这个普通类构造时也要实现对模板类的构造。
// 继承模板类
class templateB : public templateA<int>
{
private:
    float m_b;
public:
    templateB(int a,float b):templateA<int>(a),m_b(b){}
    void debugB()
    {
        qDebug()<<"templateB = "<<m_b;
    }
};


    templateB b(10,1.9999f);
    b.debug();
    b.debugB();

三 类模板继承普通类

// 普通类templateA
class templateA
{
private:
    float m_a;
public:
    templateA(float b):m_a(b){}
    void debugA()
    {
        qDebug()<<"templateA = "<<m_a;
    }
};


template <typename T1>
class templateB : public templateA
{
private:
    T1 m_b;
public:
    templateB(T1 b): templateA(0.0),m_b(b){}
    void debug()
    {
        qDebug()<<"templateB = "<<m_b;
    }

};

templateB<int>  b(111);
b.debug();

四 类模板继承类模板

template <typename T1>
class templateA
{
private:
    T1 m_A;
public:
    templateA(T1 A):m_A(A){}
    void debug()
    {
        qDebug()<<"templateA = "<<m_A;
    }
};

template <typename T1,typename T2>
class templatB : public templateA<T1>
{
private:
    T2 m_b;
public:
    templatB(T2 b):templateA<T1>(T1()),m_b(b){}
    void debug()
    {
        qDebug()<<"templateB = "<<m_b;
    }
};
templatB<int,float> testB(10.01f);
testB.debug();

五 类模板继承模板类

template <typename T1>
class templateA
{
private:
    T1 m_A;
public:
    templateA(T1 A):m_A(A){}
    void debug()
    {
        qDebug()<<"templateA = "<<m_A;
    }
};

template <typename T1>
class templatB : public templateA<int>
{
private:
    T1 m_b;
public:
    templatB(T1 b):templateA<int>(0),m_b(b){}
    void debug()
    {
        qDebug()<<"templateB = "<<m_b;
    }
};
templatB<float> testB(10.01f);
testB.debug();

六 类模板继承类型参数

template <typename T1>
class templateA
{
public:
    typedef  T1 vType;
};

template <typename T1,typename T2>
class templatB : public T2
{
private:
    typename T2::vType m_t2;
    T1 m_b;
public:
    templatB(typename T2::vType a,T1 b):m_t2(a),m_b(b){}
    void debug()
    {
        qDebug()<<"typename T2::vType = "<<m_t2<<"templateB = "<<m_b;
    }
};
templatB<float,templateA<int>> testB(10,10.01f);
testB.debug();

  • 37
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值