简单的类模板示例[C++]

本文介绍C++中类模板的定义与使用方法,并通过实例展示了如何创建类模板及其成员函数模板,同时还演示了结构模板的用法。

 

/*
*  类模板的成员函数是函数模板
*/
#include 
<iostream>
#include 
<string>
using namespace std;

/******************************************************************************
/* 类模板 - 声明
/*****************************************************************************
*/
template 
<class T> class A
{
    
public:
        A();
        A(T _a, T _b);
        T sum();
    
private:
        T a;
        T b;
};

template 
<class T1, class T2>
struct tSample
{
    T1 key;
    T2 value;
};

/******************************************************************************
/* 类模板 - 实现
/*****************************************************************************
*/
template 
<class T> A<T>::A() //类模板的成员函数是函数模板
{
    a 
= 0; b = 0;
}

template 
<class T> A<T>::A(T _a, T _b) //类模板的成员函数是函数模板
{
    a 
= _a; b = _b;
}

template 
<class T> T A<T>::sum() //类模板的成员函数是函数模板
{
    
return a + b;
}

void main()
{
    A
<int> obj1(34);
    A
<double> obj2(2.333.67);

    cout
<<"obj1.sum(3, 4)="<<obj1.sum()<<"\n"<<
        
"obj2.sum(2.33, 3.67)="<<obj2.sum()<<endl;

    tSample
<unsigned charint> array1[] = 
    {
        {
2550xffffffff},
        {
2560xfffffff},
    };

    tSample
<unsigned shortint> array2[] = 
    {
        {
2550xffffffff},
        {
2560xfffffff},
    };

    
for (int idx = 0; idx < sizeof(array1) / sizeof(array1[0]); idx++)
    {
        printf(
"template struct array1, index: %d, key: %d, value: 0x%x \n", idx, \
            array1[idx].key, array1[idx].value);
    }
    
for (idx = 0; idx < sizeof(array2) / sizeof(array2[0]); idx++)
    {
        printf(
"template struct array2, index: %d, key: %d, value: 0x%x \n", idx, \
            array2[idx].key, array2[idx].value);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值