# | Problem | Pass Rate (passed user / total user) |
---|---|---|
13750 | EE2310_Lab_12_1 |
|
13762 | EE2310_Lab_12_2 |
|
Description
Operator Overloading as Member Functions
In Lec 12-2, we practiced the operator overloading as friend functions. Now we are to re-overload them as member functions.
What you need to do
-
Re-overload
operator+()
,operator-()
,operator*()
, andoperator/()
member functions in the class definition (in "fraction.h") -
Implement these operators in "fraction.cpp". Note that they are member functions, so they belong to the Fraction class. The class name and the scope resolution operator
Fraction::
are absolutely necessary. -
Use the main function in Lec 12-2. DO NOT CHANGE MAIN and you should overload them as member functions only. otherwise your work will not be regarded as correct even if you pass all test cases. You may get PENALTY POINTS for doing those.
-
I/O testcases are the same as Lab11/Lec12.
-
You can use all other member functions from Lab 11/Lec 12. Submit everything including main().
Input
Output
Sample Input Download
Sample Output Download
Tags
Discuss
Description
Overloading >> and <<
Here we are to overload the stream extraction operator >>
and stream insertion operator <<
for the Fraction class. Note that it is not possible to overload them as member functions for the following reason: this expression cout << frac1
will be translated as cout.operator<<(frac1)
. So if we want to overload <<
as a member function, it must be the member function of the class ostream&
(cout
's class). There is no way we can overload <<
as one of Fraction's member function! Moreover, we should allow multiple operators like cout << x << y;
which will be interpreted as (cout << x) << y;
Therefore, the return type must be the same as cout
's class. Same arguments also apply to >>
.
What you need to do
-
Overload
>>
and<<
f as friend functions of Fraction. Modify the class definition accordingly. -
Main function is given. DO NOT CHANGE MAIN, otherwise your work will not be regarded as correct even if you pass all test cases. You may get PENALTY POINTS for changing main().
-
The I/O should be exactly the same as Lab11/Lec 12.
-
You can use all other member functions from Lab 11/Lec 12. Submit everything including main().
int main() {
Fraction num1, num2, ans;
char oper;
cin >> num1 >> oper >> num2;
switch (oper) {
case '+':
ans = num1 + num2; break;
case '-':
ans = num1 - num2; break;
case '*':
ans = num1 * num2; break;
case '/':
ans = num1 / num2; break;
}
cout << '(' << num1 << ") " << oper << " (" << num2 << ") = "
<< ans << endl;
return 0;
}