寒假心有点飘,特别懒,能拖就拖。。。两天没做完一道题。有点点~~~过分~~~
后来在写优先队列时,重载运算符就出现了毛病。以前只知道这么写,不知道原理,慢慢时间一长就忘记了。于是今天特意研究了一下运算符的重载。
首先。必须知道一件事。在stl库里面,有很多函数原型和运算符原型。用成员方式在进行运算符重载时,需要了解参数个数。运算符重载前后参数个数必须一致。比如对于一个二元运算符只需要一个参数。
拿个例子说吧:
template
struct less : public binary_function<_Tp, _Tp, bool> {
bool operator()(const _Tp& __x, const _Tp& __y) const {
return __x < __y;
}
};
这是function.h里面的一个<运算符的类模板。
这里是成员方式运算符重载
struct node{
char a;
int b;
float c;
double d;
bool operator<(const node a)const{
if(a else if(b else return d } }; 如果一个参数不够用时可以采用友元方式重载。 这里我直接使用今天写的优先队列的代码黏贴进去了。 附上哈夫曼树的构造方法: 有时候可能不一定使用结构体或者类,这时可以在构造优先队列时直接使用 priority_queue priority_queue struct Huffman{
char ch;
int weight;
friend bool operator < (Huffman a, Huffman b){//友元方式重载运算符
if(a.weight == b.weight){
return a.ch>b.ch;
}
else
return a.weight>b.weight;
}
/*bool operator < (const Huffman a) const{//成员方式重载运算符
if(weight == a.weight)
return ch >a.ch;
else
return weight >a.weight;*/
}
Huffman(char ch,int weight){//二参有参构造函数
this->ch = ch;
this->weight = weight;
}
Huffman(){//无参构造函数
}
};
#include