-
Notifications
You must be signed in to change notification settings - Fork 0
/
eg_OperatorOverloading.cpp
100 lines (81 loc) · 2.41 KB
/
eg_OperatorOverloading.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
#include <iostream>
using namespace std;
class Rational
{
int _n = 0;
int _d = 1;
public:
Rational(const int numerator = 0, const int denominator = 1):_n(numerator), _d(denominator) { }
Rational(const Rational& rhs) : _n(rhs._n), _d(rhs._d) { } // copy constructor
~Rational ();
int numerator() const { return _n;}
int denominator() const { return _d;}
Rational& operator = (const Rational&); // copy operator
Rational operator + (const Rational&) const;
Rational operator - (const Rational&) const;
Rational operator * (const Rational&) const;
Rational operator / (const Rational&) const;
};
Rational& Rational::operator = (const Rational& rhs)
{
if(this != &rhs)
{
_n = rhs._n;
_d = rhs._d;
}
return *this;
}
Rational Rational::operator + (const Rational& rhs) const
{
return Rational(((this->_n * rhs._d) + (this->_d * rhs._n)), this->_d * rhs._d);
}
Rational Rational::operator - (const Rational& rhs) const
{
return Rational(((this->_n * rhs._d) - (this->_d * rhs._n)), this->_d * rhs._d);
}
Rational Rational::operator * (const Rational& rhs) const
{
return Rational(this->_n * rhs._n,this->_d * rhs._d);
}
Rational Rational::operator / (const Rational& rhs) const
{
return Rational(this->_n * rhs._d,this->_d * rhs._n);
}
Rational:: ~Rational()
{
_n = 0;
_d = 1;
}
// for std::out non-member operator
std::ostream& operator << (std::ostream &o, const Rational &r)
{
if(r.denominator() == 1) return o << r.numerator();
else
{
return o << r.numerator() << "/" << r.denominator();
}
}
int main()
{
Rational a = 7; // 7/1
cout << "a is: " << a << endl;
Rational b(5,3); // 5/3
cout << "b is: " << b << endl;
Rational c = b; //copy constructor
cout << "c is: " << c << endl;
Rational d;
cout << "d is: " << d << endl;
d = c;
cout << "d is: " << d << endl;
Rational& e = d; // reference
d = e; // assignment to self!
cout << "e is: "<< e << endl;
e = e+a;
cout << "after e+a did d change?" << "d is: " << d << endl;
cout << "after e+a did d change?" << "e is: "<< e << endl;
cout << a << " + " << b << " = " << a+b << endl;
cout << a << " - " << b << " = " << a-b << endl;
cout << a << " * " << b << " = " << a*b << endl;
cout << a << " / " << b << " = " << a/b << endl;
return 0;
}