今天上了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,學習後面部分,這本書實在是太讚了!一定要好好反覆看看看!!