forked from jaege/Cpp-Primer-5th-Exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
14.52.cpp
78 lines (65 loc) · 1.83 KB
/
14.52.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
#include <iostream>
class SmallInt {
friend SmallInt operator+(const SmallInt&, const SmallInt&);
public:
SmallInt(int = 0) { } // conversion from int
operator int() const { return val; } // conversion to int
private:
std::size_t val;
};
SmallInt operator+(const SmallInt&, const SmallInt&) {
std::cout << "operator+(const SmallInt&, const SmallInt&)" << std::endl;
return SmallInt();
}
struct LongDouble {
LongDouble(double = 0.0) { }
operator double() {
std::cout << "LongDouble::operator double()" << std::endl;
return 0;
}
operator float() {
std::cout << "LongDouble::operator float()" << std::endl;
return 0;
}
LongDouble operator+(const SmallInt&) {
std::cout << "LongDouble::operator+(const SmallInt&)" << std::endl;
return *this;
}
};
LongDouble operator+(LongDouble&, double) {
std::cout << "operator+(LongDouble&, double)" << std::endl;
return LongDouble();
}
int main() {
SmallInt si;
LongDouble ld;
ld = si + ld; // Error
// candidate functions
// all built-in operator+
// LongDouble::operator+(const SmallInt&)
// operator+(LongDouble&, double)
// operator+(const SmallInt&, const SmallInt&)
//
// viable functions
// all built-in operator+
//
// best match function
// no best match function, all the following functions are equally good
// built-in operator+(int, double)
// built-in operator+(int, float)
ld = ld + si; // OK
// candidate functions
// all build-in operator+
// LongDouble::operator+(const SmallInt&)
// operator+(LongDouble&, double)
// operator+(const SmallInt&, const SmallInt&)
//
// viable functions
// all build-in operator+
// LongDouble::operator+(const SmallInt&)
// operator+(LongDouble&, double)
//
// matched function
// LongDouble::operator+(const SmallInt&)
return 0;
}