C++模板

C++有STL模板,我们使用模板能够提高开发的效率,而且模板内部的算法实现比我们一般实现的算法要更加的安全和效率高。

看如下一段代码:

#include <iostream>

void swap(int& i, int& j)
{
    int temp = i;
    i = j;
    j = temp;
}

void swap(float& i, float& j)
{
    float temp = i;
    i = j;
    j = temp;
}

int main(void)
{
    int a = 10, b = 20;
    std::cout<<"a:"<<a<<", b:"<<b<<std::endl;
    swap(a, b);
    std::cout<<"a:"<<a<<", b:"<<b<<std::endl;
    return 0;
}

结果:

a:10, b:20

a:20, b:10

若将上面的a,b类型修改成long类型,程序就会出错。无法从long int to int&,所以我们可以看出,如果参数类型改变,我们必须重载函数,由于参数类型众多,所以重载函数也需要很多,很不方便,为解决这个问题,看如下代码:

#include <iostream>

template <typename T>
void swap(T& i, T&j)
{
    T temp;
    temp = i;
    i = j;
    j = temp;
}


int main(void)
{
    long a = 10, b = 20;
    std::cout<<"a:"<<a<<", b:"<<b<<std::endl;
    swap(a, b);
    std::cout<<"a:"<<a<<", b:"<<b<<std::endl;
    int c = 100, d = 200;
    std::cout<<"c:"<<c<<", d:"<<d<<std::endl;
    swap(c, d);
    std::cout<<"c:"<<c<<", d:"<<d<<std::endl;

    return 0;

}

结果:

a:10, b:20

a:20, b:10

c:100, d:200

c:200, d:100

上面就是产生类函数模板,函数模板只适用于参数个数相同,而类型不同,且函数体实现相同到情况。

其中template <typename/class T>, T的类型可以是typename或class。

#include <iostream>

template <typename T>
class MyVector
{
public:
    MyVector(int i=20);
    ~MyVector()
    {
        delete t;
    }

    void push_back(T value)
    {
        if(offset < sizeCount)
        {
            t[offset] = value;
            offset++;
        }
    }

    const T pop_back();

private:
    T* t;
    int offset;
    int sizeCount;
};

template <typename T>
MyVector<T>::MyVector(int i)
{
    t = new T[i];
    offset = 0;
    sizeCount = i;
}
template <typename T>
const T MyVector<T>::pop_back()
{
    if(offset > 0)
    {
        --offset;
        return t[offset];
    }else
    {
        return -1;
    }
}


int main(void)
{
    MyVector<double> myvect(10);
    for(int i=0; i<10; ++i)
    {
        myvect.push_back((double)(4.8 + i));
    }
    for(int i=0; i<10; ++i)
    {
        double a = myvect.pop_back();
        std::cout<<a<<std::endl;
    }

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值