在C++的类中重载operator<和流输出

来源:互联网 发布:网络小胖结婚照 编辑:程序博客网 时间:2024/05/22 06:11

#include<iostream>
#include<queue>
using namespace std;


class Node{
 private:
  int a;
 public:
  Node(int a){
   
   this->a=a;
  }
  //定义class对象的比较函数
  friend bool operator<(const Node& a,const Node& b){
   
   if(a.a>=b.a)
    return true;
   else
    return false;
  }
  //定义class对象的流输出函数
  friend ostream& operator<<(ostream& out,const Node& a){
   return out<<a.a<<endl;
  }
};

int main(){
 
 priority_queue<Node,vector<Node> > q;   //优先队列底层使用vector来实现的。
 Node n1(4),n2(2),n3(9),n4(5);
 q.push(n1);
 q.push(n2);
 q.push(n3);
 q.push(n4);
 cout<<q.top();
 return 0;
}
//输出:2

原创粉丝点击