随笔 - 25, 文章 - 0, 评论 - 6, 引用 - 0
数据加载中……

类模板 与 模板类

类模板:类是对象的抽象,而类模板又是类的抽象,可以用模板定义出具体类(模板类)。
模板类:就是用模板定义出的具体类。
我们知道c++的多态有两种,一是运行时的多态,也就是虚函数产生多态;二就是编译时的多态,它就是由类模板产生的多态。

例子:
#include <iostream>

/// 一个类模板
template <typename T> // typename 也可以用 class
class Base
{
public:
    void PrintTypeName() // 打印出 T 的类型
    { 
        std::cout << typeid(T).name() << std::endl;
    }
};

typedef Base<int>  IntBase;        // 一个模板类
typedef Base<char> CharBase;    // 另一个模板类

int main()
{
    IntBase* pIntBase = new IntBase;
    if (NULL != pIntBase)
    {
        pIntBase->PrintTypeName();
        delete pIntBase;
        pIntBase = NULL;
    }

    CharBase* pCharBase = new CharBase;
    if (NULL != pCharBase)
    {
        pCharBase->PrintTypeName();
        delete pCharBase;
        pCharBase = NULL;
    }

    system("pause");
    return 0;
}

posted on 2013-03-13 17:11 chenjt3533 阅读(2057) 评论(0)  编辑 收藏 引用 所属分类: C/C++


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理