[ ]运算符重载和函数模板练习

今天上了C++课,发现听老师讲课和自己看书还是有很大区别的。自己看,就知道要看的是什么,将要学到的是什么,听老师讲课就是完全未知将要学到什么东西,将学到的那些也可能给我带来欣喜哦。

主要是运算符重载,竟然重载了中括号【 】,真神奇。回来自己验证了一下,还是有点问题,debug it,最后还是调通了。

类型的声明

assoc.h

#include<iostream>
#include<string>
#include<vector>
using namespace std;


class Assoc {
struct Pair {
string name;
double val;
Pair(string n=" ",double v=0):name(n),val(v) {}
};
vector<Pair> vec;
Assoc(const Assoc&);
Assoc& operator=(const Assoc&);
public:
Assoc(){};
//const double& operator[](cont string&);
double& operator[](string&);
void print_all();
};

类的定义
assoc.cc

#include<iostream>
#include<string>
#include<vector>
#include"assoc.h"
using namespace std;
 double& Assoc::operator[](string& s)
{
for(vector<Pair>::iterator p=vec.begin();p!=vec.end();p++)
if(s==p->name) return p->val;
vec.push_back(Pair(s,0));
return vec.back().val;
}
void Assoc::print_all() {
for(vector<Pair>::iterator p=vec.begin();p!=vec.end();p++)
cout<<p->name<<" "<<p->val<<endl;
}

主函数测试

#include<iostream>
#include<string>
#include<vector>
#include"assoc.cc"


int main()
{
Assoc vec;
string buf;
while(cin>>buf) vec[buf]++;
vec.print_all();
}

后来还看了函数模板的定义,使用,真是太好用了!

#include<iostream>
#include<fstream>
#include<sstream>


using namespace std;


template<typename T>
int compare (const T &v1,const T &v2)
{
if(v1<v2) return -1;
if(v2<v1) return 1;
return 0;
}
template<typename T>
T compare (const T &v)
{
if(v>=0) return v;
else return -v;
}
template<typename T>
void liu (T &os,string val)
{
os<<val;
os<<endl;
}

int main()
{
//cout<<compare(1,2)<<endl;
string s1="aa";
//string s2="a";
//cout<<compare(s1,s2)<<endl;
//cout<<compare(-1)<<endl;
//cout<<compare(-2.2)<<endl;
//cout<<compare(-3.45678901234567788)<<endl;
//liu(cout,5);
//ofstream outfile("ttt.txt");
//liu(outfile,5);
stringstream sts;
liu(sts,s1);
cout<<sts<<endl;
return 0;
}

模板类是多态、泛型编程的基础,要好好学习。再次翻开C++ PRIMER,学习后面部分,这本书实在是太赞了!一定要好好反复看看看!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值