标签:des style blog color os io div amp
13.31为你的HasPtr类定义一个<运算符,并定义一个HasPtr的vector为这个vector添加一些元素,并对它执行sort。注意何时会调用swap。
#include<iostream> #include<string> #include<new> #include<vector> #include<algorithm> using namespace std; class HasPtr { friend void swap(HasPtr&,HasPtr&); public: HasPtr(const string &s=string()):ps(new string(s)),i(0){cout<<"constructer"<<endl;} HasPtr(const HasPtr &h):i(h.i) { cout<<"copy constructer"<<endl; ps=new string; *ps=*h.ps;//只拷贝值 } HasPtr& operator=(HasPtr h) { swap(*this,h); return *this; } bool operator<(const HasPtr &h) const { return i<h.i; } ~HasPtr() { delete ps; cout<<"destructer"<<endl;} private: string *ps; int i; }; void swap(HasPtr &lhs,HasPtr &rhs) { cout<<"swap"<<endl; using std::swap; swap(lhs.ps,rhs.ps); swap(lhs.i,rhs.i); } int main() { HasPtr h; HasPtr hh(h); hh=h; swap(h,hh); vector<HasPtr> vec={h,hh}; sort(vec.begin(),vec.end()); return 0; }
标签:des style blog color os io div amp
原文地址:http://www.cnblogs.com/wuchanming/p/3928142.html