C++回顾--多态(模板)

1:群体数据

自定义类型的数据由多个基本类型或者自定义类型的元素所组成,被称为群体数据。

2:参数化多态

将程序所处理的对象的类型参数化,使得一段程序可以用于处理多种不同类型的对象。模板就是C++支持参数化多态的工具。

3:函数模板

定义形式

template <class T> 或者 template <typename T>

类型名 函数名(参数表)

{函数体的定义}

实例程序template1.c

#include <iostream>
#define N 5
using namespace std;

template <class T>
void
outputArray(T *p_array, int count);

int main() {
    int a[] = {1,2,3,4,5};
    float b[] = {1.1, 2.1, 3.1, 4.1, 5.1};
    char c[] = "hello world";
    outputArray(a, N);
    outputArray(b, N);
    outputArray(c, N);
}

// template is needed
template <class T>
void
outputArray(T *p_array, int count) {
    for (int i = 0; i < count; i ++) {
        cout<<p_array[i]<<" ";
    }
    cout<<endl;
}

4:类模板

使用类模板用户可以为类声明一种模式,使得类中的某些数据成员,某些成员函数的参数,某些成员函数的返回值能取任何类型。

4.1类模板声明

template <模板参数表>

class 类名

{类成员声明}

4.2如果需要在类外定义其他成员函数

template <模板参数表>

类型名 类名<T>::函数名(参数表)

4.3使用一个模板类来建立对象

模板<模板参数表> 对象名1,对象名2…;

实例程序template2.c

#include <iostream>
// cstdlib == stdlib.h
#include <cstdlib>
using namespace std;

template <class T>
class Store{
    private:
        T item;
        int haveValue;
    public:
        Store(void);
        T GetElem(void);
        void PutElem(T x);
};

template <class T>
Store<T>::Store():haveValue(0){}

template <class T>
T Store<T>::GetElem(void) {
    if (haveValue == 0) {
        cout<<"no item"<<endl;
        exit(1);
    }
    if (haveValue < 0) {
        cout<<"no item"<<endl;
        haveValue = 0;
        exit(1);
    }
    return item;
}

template <class T>
void Store<T>::PutElem(T x) {
    haveValue = 1;
    item = x;
}

int main() {
    Store<int> s1;
    Store<double> s2;

    // u will get 3 not 3.3
    s1.PutElem(3.3);
    int a = s1.GetElem();
    cout<<a<<endl;

    s2.PutElem(5);
    double b = s2.GetElem();
    cout<<b<<endl;

}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值