生成一个分数类并计算 使用函数重载和友缘
时间: 2023-08-10 13:05:15 浏览: 94
以下是一个使用函数重载和友元的分数类的示例:
```c++
#include <iostream>
class Fraction {
private:
int numerator;
int denominator;
public:
Fraction(int n = 0, int d = 1) : numerator(n), denominator(d) {}
friend std::ostream& operator<<(std::ostream& os, const Fraction& f) {
os << f.numerator << "/" << f.denominator;
return os;
}
friend Fraction operator+(const Fraction& f1, const Fraction& f2) {
int n = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
int d = f1.denominator * f2.denominator;
return Fraction(n, d);
}
friend Fraction operator-(const Fraction& f1, const Fraction& f2) {
int n = f1.numerator * f2.denominator - f2.numerator * f1.denominator;
int d = f1.denominator * f2.denominator;
return Fraction(n, d);
}
friend Fraction operator*(const Fraction& f1, const Fraction& f2) {
int n = f1.numerator * f2.numerator;
int d = f1.denominator * f2.denominator;
return Fraction(n, d);
}
friend Fraction operator/(const Fraction& f1, const Fraction& f2) {
int n = f1.numerator * f2.denominator;
int d = f1.denominator * f2.numerator;
return Fraction(n, d);
}
friend bool operator==(const Fraction& f1, const Fraction& f2) {
return f1.numerator * f2.denominator == f2.numerator * f1.denominator;
}
friend bool operator!=(const Fraction& f1, const Fraction& f2) {
return !(f1 == f2);
}
friend bool operator<(const Fraction& f1, const Fraction& f2) {
return f1.numerator * f2.denominator < f2.numerator * f1.denominator;
}
friend bool operator<=(const Fraction& f1, const Fraction& f2) {
return (f1 < f2) || (f1 == f2);
}
friend bool operator>(const Fraction& f1, const Fraction& f2) {
return !(f1 <= f2);
}
friend bool operator>=(const Fraction& f1, const Fraction& f2) {
return !(f1 < f2);
}
};
int main() {
Fraction f1(1, 2);
Fraction f2(3, 4);
std::cout << "f1 = " << f1 << std::endl;
std::cout << "f2 = " << f2 << std::endl;
Fraction f3 = f1 + f2;
std::cout << "f1 + f2 = " << f3 << std::endl;
Fraction f4 = f1 - f2;
std::cout << "f1 - f2 = " << f4 << std::endl;
Fraction f5 = f1 * f2;
std::cout << "f1 * f2 = " << f5 << std::endl;
Fraction f6 = f1 / f2;
std::cout << "f1 / f2 = " << f6 << std::endl;
bool isEqual = f1 == f2;
std::cout << "f1 == f2 is " << (isEqual ? "true" : "false") << std::endl;
bool isNotEqual = f1 != f2;
std::cout << "f1 != f2 is " << (isNotEqual ? "true" : "false") << std::endl;
bool isLessThan = f1 < f2;
std::cout << "f1 < f2 is " << (isLessThan ? "true" : "false") << std::endl;
bool isLessThanOrEqual = f1 <= f2;
std::cout << "f1 <= f2 is " << (isLessThanOrEqual ? "true" : "false") << std::endl;
bool isGreaterThan = f1 > f2;
std::cout << "f1 > f2 is " << (isGreaterThan ? "true" : "false") << std::endl;
bool isGreaterThanOrEqual = f1 >= f2;
std::cout << "f1 >= f2 is " << (isGreaterThanOrEqual ? "true" : "false") << std::endl;
return 0;
}
```
这个示例中,分数类 `Fraction` 重载了一系列运算符,包括加、减、乘、除、相等、不相等、小于、小于等于、大于和大于等于运算符。所有运算符都是友元函数,它们都使用了 C++ 的函数重载机制。在 `main()` 函数中,我们创建了两个分数对象 `f1` 和 `f2`,并演示了这些运算符的使用。
阅读全文