zoukankan      html  css  js  c++  java
  • c++模板杂谈

    实验环境 linux mint 下 Qt 5.11

    说白了,模板就是搭个函数,类的框架,具体实现的时候往里面填充内容,或者我们可以把类型名想作一个占位符号

    • 函数模板----俗气的比大小
    #include <iostream>
    #include<string.h>
    using namespace std;
    
    
    template <class TYPE>
    TYPE returnmax(TYPE x, TYPE y)
    {
        return (x>y)?x:y;
    }
    
    char*  returnmax(char* x,char* y)
    {
        return (strcmp(x,y)<0)?x:y;
    }
    
    
    int main()
    {
        cout << "Hello World!" << endl;
        char* chorum2 ="你你你你要跳舞吗";
        char* chorum1 ="每当浪潮来临的时候,你会不会也伤心";
        cout<<returnmax(chorum1,chorum2)<<endl;
        cout<<returnmax(99,888)<<endl;
        return 0;
    }

    输出结果:

    •  类模板---使数据结构和算法不受所包含的元素类型的影响

    目录结构

    •  头文件
    #ifndef XA_H
    #define XA_H
    #include<iostream>
    #include<string.h>
    using namespace std;
    
    template <class sometype>
    class xa
    {
    public:
        xa(sometype x)
        {
            myx = x;
        }
        void showme()
        {
            cout<<this->myx<<endl;
        }
    private:
        sometype myx;
    };
    
    #endif // XA_H
    • 具体调用
    #include <iostream>
    
    using namespace std;
    #include "xa.h"
    int main()
    {
        xa<char*> myx("瑞典鹰狮战斗机");
        myx.showme();
        xa<int> another(888);
        another.showme();
    
        //cout << "Hello World!" << endl;
        return 0;
    }

    输出结果:

    • 一个类模板的定义与实现 主要特征是构造函数参数列表中第一个参数可能是字符指针或者整型数

    项目构成

      •  
    • mytempl.h

    #ifndef MYTEMPL_H
    #define MYTEMPL_H
    
    template <class wenwa>
    class mytempl
    {
    public:
        mytempl(wenwa name,int age);
        wenwa name;
        int age;
        void showme();
    };
    
    #endif // MYTEMPL_H
    • mytempl.cpp

    #include "mytempl.h"
    #include <iostream>
    using namespace std;
    template <class wenwa>
    mytempl<wenwa>::mytempl(wenwa name,int age)
    {
        this->name=name;
        this->age=age;
    }
    
    template <class wenwa>
    void mytempl<wenwa>::showme()
    {
        if(typeid(wenwa)==typeid(int))
        {
                cout<<"哇哒吸袜~三井重工"<<this->name<<"号防卫机器人"<<endl;
                cout<<"武器装备:"<<this->age<<"毫米火炮"<<endl;
        }
        else
        {
            cout<<"大家好!我是 "<<this->name<<endl;
            cout<<"那什么尺寸:"<<this->age<<"cm"<<endl;
        }
    }
    • main.cpp

    #include <iostream>
    #include "mytempl.cpp"
    
    using namespace std;
    
    int main()
    {
        mytempl<int> robot(888,120);
        robot.showme();
        cout<<" ......."<<endl;
        mytempl<char*> cpc("昌仔",22);
        cpc.showme();
        return 0;
    }

    输出结果:

  • 相关阅读:
    BZOJ
    Codeforces
    GYM
    UOJ
    Java集合之Queue
    【HIHOCODER 1478】 水陆距离(BFS)
    Java集合之Stack
    Java集合之Vector
    Java多线程入门Ⅱ
    【HIHOCODER 1604】股票价格II(堆)
  • 原文地址:https://www.cnblogs.com/saintdingspage/p/12247418.html
Copyright © 2011-2022 走看看