-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ex13_31.h
59 lines (51 loc) · 1.2 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
58
59
//
// 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() const { 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