1
1
#include < iostream>
2
2
#include < string>
3
3
#include < memory>
4
+ #include < vector>
5
+ #include < algorithm>
4
6
5
7
using namespace std ;
6
8
// 定义行为像值的类
7
9
class HasPtr
8
10
{
9
11
private:
10
- int i;
11
12
string* ps;
13
+ int i;
14
+
12
15
public:
13
- HasPtr (const string& s = string()):
14
- ps (new string(s)), i(0 ){}
15
- HasPtr (HasPtr& s):
16
+ HasPtr (const string& s = string(), int a = 0 ):
17
+ ps (new string(s)), i(a ){}
18
+ HasPtr (const HasPtr& s):
16
19
ps (new string(*s.ps)), i(s.i){}
17
20
HasPtr& operator =(const HasPtr& p);
21
+ friend bool lessthan (const HasPtr& s1, const HasPtr& s2);
22
+ friend ostream& operator <<(ostream& os, const HasPtr& P);
23
+ friend void swap (HasPtr& , HasPtr&);
18
24
~HasPtr ()
19
25
{
20
26
delete ps;
21
27
}
22
28
};
23
-
29
+ bool lessthan (const HasPtr& s1, const HasPtr& s2)
30
+ {
31
+ if (s1.i < s2.i )
32
+ {
33
+ return true ;
34
+ }
35
+ else
36
+ {
37
+ return false ;
38
+ }
39
+ }
40
+ ostream& operator <<(ostream& os, const HasPtr& p)
41
+ {
42
+ os << *p.ps << " " << p.i ;
43
+ }
24
44
HasPtr& HasPtr::operator =(const HasPtr& p)
25
45
{
26
46
i = p.i ;
@@ -30,6 +50,13 @@ HasPtr& HasPtr::operator=(const HasPtr& p)
30
50
return *this ;
31
51
}
32
52
53
+ inline void swap (HasPtr& lsh, HasPtr& rsh)
54
+ {
55
+ using std::swap;
56
+ swap (lsh.ps , rsh.ps );
57
+ swap (lsh.i , rsh.i );
58
+ cout << " using swap()" << endl;
59
+ }
33
60
// 定义行为像指针的类
34
61
class PHasPtr
35
62
{
@@ -104,5 +131,21 @@ class TreeNode
104
131
};
105
132
int main ()
106
133
{
134
+ HasPtr a (" xiangyu" , 2 );
135
+ HasPtr b (" liuchang" , 1 );
136
+ HasPtr c (" liuzheng" , 3 );
137
+ swap (a, b);
138
+ cout << " a: " << a << endl;
139
+ cout << " b: " << b << endl;
140
+ vector<HasPtr> HasVec;
141
+ HasVec.push_back (a);
142
+ HasVec.push_back (b);
143
+ HasVec.push_back (c);
144
+ sort (HasVec.begin (), HasVec.end (), lessthan);
145
+ for (auto it : HasVec)
146
+ {
147
+ cout << it << endl;
148
+ }
149
+
107
150
return 0 ;
108
151
}
0 commit comments