-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoperator-overloading.cpp
More file actions
82 lines (66 loc) · 1.99 KB
/
operator-overloading.cpp
File metadata and controls
82 lines (66 loc) · 1.99 KB
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
#include <iostream>
#include <string>
using std::cout;
using std::cin;
class RasyonelSayi{
private:
int pay,payda;
public:
RasyonelSayi();
RasyonelSayi(int x,int y);
RasyonelSayi operator+(const RasyonelSayi &rs);
std::string toString();
friend std::ostream& operator<<(std::ostream &out, RasyonelSayi &rs);
friend void operator>>(std::istream &in, RasyonelSayi &rs);
};
std::ostream& operator<<(std::ostream &out, RasyonelSayi &rs){
out << rs.pay << "/" << rs.payda;
return out;
}
int main(){
RasyonelSayi s1(1,2);
RasyonelSayi s2(2,3);
// "<<" overloading
cout << s1 << "\n";
// "+" overloading
RasyonelSayi sum = s1 + s2;
cout << sum;
RasyonelSayi s3;
// ">>" overloading
cin >> s3;
cout << "rasyonel sayi: " << s3;
}
//class functions
RasyonelSayi::RasyonelSayi(){};
RasyonelSayi::RasyonelSayi(int x,int y){
pay = x;
payda = y;
}
RasyonelSayi RasyonelSayi::operator+(const RasyonelSayi &rs){
return RasyonelSayi(pay*rs.payda+payda*rs.pay, payda*rs.payda);
}
std::string RasyonelSayi::toString(){
return std::to_string(pay) + "/" + std::to_string(payda);
}
void operator>>(std::istream &in, RasyonelSayi &rs){
/* --if you wanna ask numerator-denominator you can use this code below.
int x,y;
cout <<"pay: ";
in >> x;
cout <<"payda: ";
in >> y;
rs.pay = x;
rs.payda = y;
*/
// --also if you wanna take inputs like "3/4" you can use this--
std::string num; //3/4
in >> num;
int index = num.find('/'); //the method "find" also returns size_t ..
if(index == 0){ //if you used size_t type above you should replace condition to ( index == std::string::npos )
rs.pay = std::stoi(num);
rs.payda = 1;
return; // exits function
}
rs.pay = std::stoi( num.substr(0,index) );
rs.payda = std::stoi( num.substr(index+1) );
}