#include <iostream>
using namespace std;
class Fraction {
int m_numerator = 0;
int m_denominator = 1;
friend void makeCommon(Fraction& a, Fraction& b);
public:
int getnumerator() { return m_numerator; }
int getdenominator() { return m_denominator; }
double value()const;
void reduce();
Fraction(int above = 0, int below = 1) :
m_numerator(above), m_denominator(below) {
cout << "Constructor called" << endl;
}
Fraction(const Fraction& rhs) :m_numerator(rhs.m_numerator),
m_denominator(rhs.m_numerator) {
cout << "Copy constructor called" << endl;
}
Fraction(Fraction& rhs) :m_numerator(rhs.m_numerator),
m_denominator(rhs.m_denominator) {
cout << "Copy constructor called<<endl;";
}
int ~Fraction() {};
private:
int gcd(int a, int b);
};
void makeCommon(Fraction& a, Fraction& b) {
a.m_numerator *= b.m_denominator;
b.m_numerator *= a.m_denominator;
b.m_denominator = a.m_denominator *= b.m_denominator;
}
Fraction operator/( Fraction& left, Fraction& right) {
Fraction result(left.getnumerator() * right.getdenominator(), \
left.getnumerator() * right.getnumerator());
return result;
}
Fraction divide1(Fraction& divident, Fraction& divisor) {
return Fraction(divident.getnumerator() * divisor.getdenominator(),
divident.getdenominator() * divisor.getnumerator());
}
Fraction divide2(Fraction divident, Fraction divisor) {
Fraction result(divident.getnumerator() * divisor.getdenominator(),
divident.getdenominator() * divisor.getnumerator());
return result;
}
double Fraction::value()const {
return static_cast<double>(m_numerator) / m_denominator;
}
void Fraction::reduce() {
int n = gcd(m_numerator, m_denominator);
m_denominator /= n;
m_numerator /= n;
}
int Fraction::gcd(int a, int b)
{
if (b != 0) {
return gcd(b, a % b);
}
else
return a;
}
int main() {
Fraction a;
cout << endl;
Fraction b(a);
cout << endl;
Fraction c = Fraction(3, 2);
cout << endl;
Fraction d1(2, 3), d2(4, 5);
cout << endl;
Fraction e1 = divide1(d1, d2);
cout << endl;
Fraction e2 = divide2(d1, d2);
cout << endl;
return 0;
}
//Constructor called
//Copy constructor called << endl;
//Constructor called
//Constructor called
//Constructor called
//Constructor called
//Copy constructor called << endl; Copy constructor called << endl; Constructor called
//Copy constructor called
类的定义与基本操作
最新推荐文章于 2021-10-26 17:13:27 发布