zoukankan      html  css  js  c++  java
  • C++的模板类应用举例

    设有程序

    $ cat -n base2.cpp
         1    #include <iostream>
         2    using namespace std;
         3    class Base
         4    {
         5        int x;
         6        public:
         7            Base(int i) {x=i;}
         8            int getx() {return x;}
         9            void disp() {cout<<"The value of x in Base is: "<<x<<endl;}
        10    };
        11    template <class T>
        12    class Derived:public Base
        13    {
        14        T y;
        15        public:
        16            Derived(T a,int j):Base(j){y=a;}
        17            T gety(){return y;}   
        18            void disp()
        19            {cout<<"The value of y in Derived is : "<<y<<", and x in Derived is: "<<gety()<<endl;}
        20    };
        21    int main()
        22    {
        23        Base obj_B(888);
        24        obj_B.disp();
        25        Derived<int> obj_D1(1,2);
        26        Derived<double> obj_D2(8.8,6);
        27        Derived<char *> obj_D3("zrf",10);
        28        Derived<char> obj_D4('=',20);
        29        obj_D1.disp();
        30        obj_D2.disp();
        31        obj_D3.disp();
        32        obj_D4.disp();
        33   
        34    }

    则其运行结果为:

    $ ./base2
    The value of x in Base is: 888
    The value of y in Derived is : 1, and x in Derived is: 1
    The value of y in Derived is : 8.8, and x in Derived is: 8.8
    The value of y in Derived is : zrf, and x in Derived is: zrf
    The value of y in Derived is : =, and x in Derived is: =

    然后将template <class T>改为template <typename T>,重新编译,运行结果一样,这样就证明了class T等价于typename T

  • 相关阅读:
    IOS开发系列之阿堂教程:玩转IPhone客户端和Web服务端交互(客户端)实践
    详解基于linux环境MySQL搭建与卸载
    详解Redis基本命令
    浅谈基于Linux的Redis环境搭建
    浅谈Linux基本命令
    浅谈基于Intellij IDEA Maven的配置与使用
    浅谈SpringMVC执行过程
    浅析关于java的一些基础问题(上篇)
    软件架构应关心的若干要素
    详解mybatis映射配置文件
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2053815.html
Copyright © 2011-2022 走看看