用c++编写分数的运算符重载
时间: 2023-06-09 22:03:10 浏览: 118
好的,让我来回答您的问题。用C++编写分数的运算符重载涉及到分数对象的加、减、乘、除等运算符重载操作。以下是一个示例代码,可供参考:
```c++
class Fraction {
public:
Fraction(int num = 0, int den = 1)
: m_numerator(num), m_denominator(den) {
reduce();
}
int getNumerator() const { return m_numerator; }
int getDenominator() const { return m_denominator; }
Fraction operator+(const Fraction& other) const {
int num = m_numerator * other.m_denominator + m_denominator * other.m_numerator;
int den = m_denominator * other.m_denominator;
return Fraction(num, den);
}
Fraction operator-(const Fraction& other) const {
int num = m_numerator * other.m_denominator - m_denominator * other.m_numerator;
int den = m_denominator * other.m_denominator;
return Fraction(num, den);
}
Fraction operator*(const Fraction& other) const {
int num = m_numerator * other.m_numerator;
int den = m_denominator * other.m_denominator;
return Fraction(num, den);
}
Fraction operator/(const Fraction& other) const {
int num = m_numerator * other.m_denominator;
int den = m_denominator * other.m_numerator;
return Fraction(num, den);
}
private:
int m_numerator;
int m_denominator;
int gcd(int a, int b) const {
return b == 0 ? a : gcd(b, a % b);
}
void reduce() {
int common = gcd(m_numerator, m_denominator);
m_numerator /= common;
m_denominator /= common;
}
};
```
这里定义了一个名为Fraction(分数)的类,重载了加、减、乘、除运算符,可以通过该类进行分数的运算。
阅读全文