forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex19_21_22_23_24_25.cpp
113 lines (105 loc) · 2.54 KB
/
ex19_21_22_23_24_25.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <iostream>
#include <string>
using std::string;
class Sales_data{
public:
Sales_data() = default;
~Sales_data() = default;
Sales_data(int i):a(i){}
Sales_data(const Sales_data &rhs):a(rhs.a){}
Sales_data& operator=(const Sales_data&rhs){
a = rhs.a;
return *this;
}
private:
int a = 0;
};
class Token{
public:
Token():tok(INT),ival(0){}
Token(const Token&t): tok(t.tok){copyUnion(t);}
~Token(){
if(tok == STR) sval.~string();
if(tok == SAL) item.~Sales_data();
}
Token& operator=(Token &&);
Token(Token&&);
Token& operator=(const Token&);
Token& operator=(const string&);
Token& operator=(const int&);
Token& operator=(const char&);
Token& operator=(const Sales_data&);
private:
enum { INT, CHAR, STR, SAL} tok;
union{
char cval;
int ival;
std::string sval;
Sales_data item;
};
void copyUnion(const Token&);
//move edition
void copyUnion(Token&&);
};
void Token::copyUnion(Token&& t){
switch (t.tok) {
case INT : ival = t.ival; break;
case CHAR : cval = t.cval; break;
case STR : std::move(t.sval);break;
case SAL : std::move(t.item); break;
}
}
void Token::copyUnion(const Token &t){
switch (t.tok) {
case INT : ival = t.ival; break;
case CHAR : cval = t.cval; break;
case STR : new(&sval) string(t.sval);break;
case SAL : new(&item) Sales_data(t.item); break;
}
}
Token& Token::operator=(const Token&t){
if(tok == STR && t.tok != STR) sval.~string();
if(tok == SAL && t.tok != SAL) item.~Sales_data();
if(tok == STR && t.tok == STR) sval = t.sval;
if(tok == SAL && t.tok == SAL) item = t.item;
else copyUnion(t);
tok = t.tok;
return *this;
}
//move constructor
Token& Token::operator=(Token&& t){
if(this != &t){
this->~Token();
copyUnion(t);
tok = std::move(t.tok);
}
return *this;
}
Token::Token(Token &&t){
copyUnion(t);
tok = std::move(t.tok);
}
Token& Token::operator=(const Sales_data& rhs){
if(tok == STR) sval.~string();
if(tok == SAL)
item = rhs;
else
new(&item) Sales_data(rhs);
tok = SAL;
return *this;
}
Token& Token::operator=(const int& i){
if(tok == STR) sval.~string();
if(tok == SAL) item.~Sales_data();
ival = i;
tok = INT;
return *this;
}
int main(int argc, char const *argv[]) {
Token s;
Sales_data sal(5);
s = sal;
int i = 5;
std::cout << i << std::endl;
return 0;
}