-
Notifications
You must be signed in to change notification settings - Fork 246
/
13.8.cpp
41 lines (33 loc) · 846 Bytes
/
13.8.cpp
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
#include <string>
#include <iostream>
class HasPtr {
public:
HasPtr(const std::string &s = std::string())
: ps(new std::string(s)), i(0) {}
HasPtr(const HasPtr &ori)
: ps(new std::string(*ori.ps)), i(ori.i) {}
HasPtr &operator=(const HasPtr &rhs);
const std::string &get() const { return *ps; }
void set(const std::string &s) { *ps = s; }
private:
std::string *ps;
int i;
};
HasPtr &HasPtr::operator=(const HasPtr &rhs) {
// This copy-assignment operator is wrong, see ex13.23 for correct version.
delete ps;
ps = new std::string(*rhs.ps);
i = rhs.i;
return *this;
}
int main() {
HasPtr hp1 = "World";
HasPtr hp2 = hp1;
HasPtr hp3;
hp3 = hp1;
hp1.set("Hello");
std::cout << hp1.get() << std::endl;
std::cout << hp2.get() << std::endl;
std::cout << hp3.get() << std::endl;
return 0;
}