-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcpp1.cpp
89 lines (80 loc) · 1.45 KB
/
cpp1.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
#include <stdio.h>
#include <stdint.h>
#include <wchar.h>
#include <stdexcept>
#define MUL 1000000.0
class MoneyOverflowException: public std::runtime_error
{
public:
MoneyOverflowException(): std::runtime_error("Money Overflow") {}
};
class MONEY
{
public:
MONEY(double d) {
m_data[0] = (int64_t)(d * MUL);
m_data[1] = 0;
}
double ToDouble() const {
return m_data[0] / MUL;
}
MONEY &Add(double d)
{
if (ToDouble() + d > 10000.0)
{
throw MoneyOverflowException();
}
m_data[0] += (int64_t)(d * MUL);
}
private:
int64_t m_data[2];
};
class SBOStringData
{
public:
SBOStringData(const MONEY &m) {
m_str = new wchar_t[50];
#ifdef _WINDOWS
m_len = swprintf(m_str, L"%.2lf", m.ToDouble());
#else
m_len = swprintf(m_str, 50, L"%.2lf", m.ToDouble());
#endif
}
~SBOStringData() {
delete m_str;
}
private:
wchar_t *m_str;
int m_len;
friend class SBOString;
};
class SBOString
{
public:
SBOString(const MONEY &m) {
m_strData = new SBOStringData(m);
}
~SBOString() {
delete m_strData;
}
const wchar_t *GetBuffer() const {
return m_strData->m_str;
}
private:
SBOStringData *m_strData;
};
int main()
{
MONEY m(8888.123);
try {
for (int i=0; i<10; ++i) {
m.Add(234.512);
SBOString s(m);
printf("i=%d, %lf, %ls\n", i, m.ToDouble(), s.GetBuffer());
}
}
catch (std::exception &e) {
printf("Exception: %s\n", e.what());
}
return 0;
}