write an overloaded friend ostream insertion operator function that allows a Fraction object to be output and appear in the form num/denom, using a cout statement. b. Write an overloaded friend istream extraction operator function that allows fractions in the form a/b to be input and assigned to a Fraction object.
时间: 2024-03-03 13:50:16 浏览: 86
overloaded function function is ambiguous(解决方案).md
Sure, I can help you with that!
Here is the implementation of the overloaded friend ostream insertion operator function for the Fraction class:
```c++
#include <iostream>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int num, int denom) : numerator(num), denominator(denom) { }
friend std::ostream& operator<<(std::ostream& os, const Fraction& frac);
};
std::ostream& operator<<(std::ostream& os, const Fraction& frac) {
os << frac.numerator << "/" << frac.denominator;
return os;
}
```
And here is the implementation of the overloaded friend istream extraction operator function for the Fraction class:
```c++
#include <iostream>
#include <sstream>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int num, int denom) : numerator(num), denominator(denom) { }
friend std::istream& operator>>(std::istream& is, Fraction& frac);
};
std::istream& operator>>(std::istream& is, Fraction& frac) {
std::string input;
is >> input;
std::stringstream ss(input);
int num, denom;
char slash;
ss >> num >> slash >> denom;
frac.numerator = num;
frac.denominator = denom;
return is;
}
```
You can use these overloaded operators to output and input Fraction objects as follows:
```c++
int main() {
Fraction f1(3, 4);
std::cout << f1 << std::endl; // outputs "3/4"
Fraction f2(0, 1);
std::cin >> f2; // inputs a Fraction from standard input in the form "num/denom"
std::cout << f2 << std::endl; // outputs the input Fraction
return 0;
}
```
I hope this helps! Let me know if you have any other questions.
阅读全文