forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex13_31.h
57 lines (49 loc) · 1.21 KB
/
ex13_31.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// ex13_31.h
// Exercise 13.31
//
// Created by pezy on 1/23/15.
// Copyright (c) 2015 pezy. All rights reserved.
//
// Give your class a < operator and define a vector of HasPtrs.
// Give that vector some elements and then sort the vector.
// Note when swap is called.
//
// See ex13_30.h
#ifndef CP5_ex13_11_h
#define CP5_ex13_11_h
#include <string>
#include <iostream>
class HasPtr {
public:
friend void swap(HasPtr&, HasPtr&);
friend bool operator<(const HasPtr &lhs, const HasPtr &rhs);
HasPtr(const std::string &s = std::string()) : ps(new std::string(s)), i(0) { }
HasPtr(const HasPtr &hp) : ps(new std::string(*hp.ps)), i(hp.i) { }
HasPtr& operator=(HasPtr tmp) {
this->swap(tmp);
return *this;
}
~HasPtr() {
delete ps;
}
void swap(HasPtr &rhs) {
using std::swap;
swap(ps, rhs.ps);
swap(i, rhs.i);
std::cout << "call swap(HasPtr &rhs)" << std::endl;
}
void show() { std::cout << *ps << std::endl; }
private:
std::string *ps;
int i;
};
void swap(HasPtr& lhs, HasPtr& rhs)
{
lhs.swap(rhs);
}
bool operator<(const HasPtr &lhs, const HasPtr &rhs)
{
return *lhs.ps < *rhs.ps;
}
#endif