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

  • 相关阅读:
    python无意中发现的
    mysql 中关于周和月份的表示
    列表表达式
    python编码
    bugfree安装
    python练习题代码
    根据用户名或者厂商名称生成相关的弱口令
    获取QQ企业邮箱通讯录PY脚本
    SQL注入POC
    乌云精华漏洞爬取匹配
  • 原文地址:https://www.cnblogs.com/djcsch2001/p/2053815.html
Copyright © 2011-2022 走看看