C++模板函数实践1

Posted do-your-best

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++模板函数实践1相关的知识,希望对你有一定的参考价值。

实践如下:

#include <iostream>
#include <typeinfo>

using namespace std;

class Bean
private:
    int a;
public:
    Bean()
        this->a = 0;
    
    Bean(int a)
        this->a = a;
    
    ~Bean()
    int getA()
        return a;
    
    // 重载==操作符
    bool operator==(Bean to)
        cout<<"Bean重载操作符==进行比较"<<endl;
        return this->a == to.a;
    
    bool operator>(Bean to)
        cout<<"Bean重载操作符>进行比较"<<endl;
        return this->a > to.a;
    
    friend ostream & operator<<(ostream &out, Bean obj)
        cout<<"bean a值:"<< obj.a<<endl;
        return out;
    
;

// 模板方法实践
template<class Type>
Type maxV(Type a, Type b)
    //cout<<" typeid(a).name(): "<< typeid(a).name()<<endl;
    return a > b ? a : b;

// 重载方法
int maxV(int a, int b)
    cout<<" 重载函数"<<endl;
    return a > b ? a : b;


template<class K, class V>
class MyMap
private:
    K keys[10];
    V values[10];
    int count = 0;
public:
    void put(K key, V value)
        keys[count] = key;
        values[count] = value;
        count++;
    
    V get(K key)
//        if(key == NULL)
//            cout << "入参key为空,返回NULL" << endl;
//            return (V)NULL;
//        
        for(int i = 0; i< count; i++)
            if(keys[i] == key)
                cout << "命中下标:" << i << endl;
                return values[i];
            
        
        cout << "找不到key,返回NULL" << endl;
        return (V)NULL;
    
;


int main() 

    cout << "模板函数1 实践:" << endl;

    cout<<"maxV(11,220): "<<maxV(11,220)<<endl;
    cout<<"maxV(11.1f,220.1f): "<<maxV(11.1f,220.1f)<<endl;
    cout<<"max(11.1L,220.1L): "<<maxV(11.1L,220.1L)<<endl;
    cout<<"max(‘a‘,‘c‘): "<<maxV(a,c)<<endl<<endl;

    MyMap<int,double> map;
    map.put(11, 100);
    map.put(22, 200);
    map.put(33, 333);
    map.put(44, 444);
    cout<<"map.get(1): "<<map.get(11)<<endl;
    cout<<"map.get(44): "<<map.get(44)<<endl;
    cout<<"map.get(55): "<<map.get(55)<<endl;
    cout<<"map.get(1): "<<map.get((int)NULL)<<endl;


    MyMap<Bean,int> beanMap;
    beanMap.put(Bean(1), 11111);
    beanMap.put(Bean(11), 11);
    beanMap.put(Bean(111), 111);
    cout<<"beanMap.get(Bean(1)): "<<beanMap.get(Bean(1))<<endl;

    cout<<"maxV(Bean(1),Bean(11)): "<<maxV(Bean(1),Bean(11))<<endl<<endl;


    cout << "\\n模板函数 end." << endl;

    return 0;

输出结果:

技术图片

 

以上是关于C++模板函数实践1的主要内容,如果未能解决你的问题,请参考以下文章

《深入实践C++模板编程》之六——标准库中的容器

C++提高编程

C++提高编程模板 or 泛型

C++模板(函数模板/类模板)

C++模板(函数模板/类模板)

[转]C++函数模板与模板函数