C++模板函数实践1
2024-09-24 16:16:03
实践如下:
#include <iostream>
#include <typeinfo> using namespace std; class Bean{
private:
int a;
public:
Bean(){
this->a = ;
}
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[];
V values[];
int count = ;
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 = ; 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(,)<<endl;
cout<<"maxV(11.1f,220.1f): "<<maxV(11.1f,220.1f)<<endl;
cout<<"max(11.1L,220.1L): "<<maxV(.1L,.1L)<<endl;
cout<<"max('a','c'): "<<maxV('a','c')<<endl<<endl; MyMap<int,double> map;
map.put(, );
map.put(, );
map.put(, );
map.put(, );
cout<<"map.get(1): "<<map.get()<<endl;
cout<<"map.get(44): "<<map.get()<<endl;
cout<<"map.get(55): "<<map.get()<<endl;
cout<<"map.get(1): "<<map.get((int)NULL)<<endl; MyMap<Bean,int> beanMap;
beanMap.put(Bean(), );
beanMap.put(Bean(), );
beanMap.put(Bean(), );
cout<<"beanMap.get(Bean(1)): "<<beanMap.get(Bean())<<endl; cout<<"maxV(Bean(1),Bean(11)): "<<maxV(Bean(),Bean())<<endl<<endl; cout << "\n模板函数 end." << endl; return ;
}
输出结果:
最新文章
- [原创]cocos2d-x研习录-第三阶 特性之加速度传感器
- 关于python怎样编写登录接口
- 优先级反转实验,使用信号量实现【RT-Thread学习笔记 5】
- springMVC学习笔记(五)
- fopen()、 file_get_contents() 通过url获取链接内容
- Python之路,Day13-----暂无正在更新中
- 依赖注入与Unity(一) 介绍
- ajax获取后台传递的json数据
- this.button1.Click += new System.EventHandler(this.button1_Click);
- 编程零基础应当如何开始学习 Python?
- [NOIp 2013]货车运输
- 【RL-TCPnet网络教程】第2章 嵌入式网络协议栈基础知识
- 1. vs code 设置快捷键与eclipse一样
- hibernate多对多映射文件的配置
- [JOISC2014]ストラップ
- python学习之老男孩python全栈第九期_day001知识点总结
- 【转】Linux 高级的视角来查看Linux引导过程
- 项目内部IT/电商/信息化类简报,分享电子版
- 使用 data.table 包操作数据
- 前端切图要选择png和jpg呢?