今天上了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,学习后面部分,这本书实在是太赞了!一定要好好反复看看看!!