C++模板

#include <iostream>

using namespace std;

template <class T1,class T2>

class Test
{
private:
    T1 m_a;
    T2 m_b;
public:
    Test(T1 a,T2 b)
    {
        m_a = a;
	m_b = b;
    }

    T1 get_val1();
    T2 get_val2();
};


template<class T1,class T2>
T1 Test<T1,T2>::get_val1()
{
    return m_a;
}

template<class T1,class T2>
T2 Test<T1,T2>::get_val2()
{
    return m_b;
}

int main()
{
    Test<double,int>a(1.2,3);
    cout << a.get_val1() << endl;
    cout << a.get_val2() << endl;

    return 0;
}

栈操作

#include <iostream>
using namespace std;

template<class T>
class Stack
{
private:
    int Max_size;
    int top;
    T * stackptr;
public:
    Stack(int s);
    ~Stack(){delete [] stackptr;}

    bool is_Empty() const {return (top == -1);}
    bool is_Full() const {return (top == Max_size);}

    bool push(const T& t);
    bool pop(T& t);
};

template<class T>
Stack<T>::Stack(int s)
{
    Max_size = s > 0 ? s : 10;
    top = -1;
    stackptr = new T[Max_size];
}

template<class T>
bool Stack<T>::push(const T& t)
{
    if(!is_Full())
    {
        top++;
	stackptr[top] = t;
	return true;
    }

    return false;
}

template <class T>
bool Stack<T>::pop(T& t)
{
     if(!is_Empty())
     {
         t = stackptr[top--];
         return true;
     }
    
     return false;
}
int main()
{
    Stack<double> double_stack(5);

    double f = 0.1;

    /*for(int i = 0; i < 5; i++)
    {
        double_stack.push(f);
	f += 1;
    }*/

    while(double_stack.push(f))
    {
        cout << f << endl;
	f = f + 1;
    }

    while(double_stack.pop(f))
    {
        cout << f << endl;
    }

    return 0;
}

 普通类 -> 模板类

#include <iostream>
using namespace std;


class Base
{
private:
    int m_a;
protected:
    int m_b;
public:
    Base(int a,int b)
    {
        m_a = a;
	m_b = b;
    }

    void show()
    {
    
        cout << m_a << "," << m_b << endl;
    }

};


template<class T>
class Derived:public Base
{
private:
    T m_t;
public:

    Derived(T t):Base(0,0)
    {
        m_t = t;
    }

    T get_t()
    {
        return m_t;
    }

};



int main()
{
    Derived<double> d(1.2);

    d.show();

    double a = d.get_t();

    cout << a << endl;

    return 0;
}

 模板类->模板类

#include <iostream>

using namespace std;

template <class T>
class Base
{
public:
    void test(T t)
    {
        cout << "base::t :" << t << endl;
    }

};


template<class T1,class T2>
class Derived:public Base<T2>
{
public:
    void test2(T1 t1, T2 t2)
    {
    
        cout << "Derived::" << t1 << "," << t2 << endl;
    }
};


int main()
{
    Derived<int,double> d1;

    d1.test(1.23);
    d1.test2(12,34);

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值