所以基本上我正在尝试做一个分数类。它将从用户输入中获取分数并执行加法。例如,我输入 1 5 和 1 7 ,对于加法,它将打印出 12/35。
这是我的.h类:
#include <string>
#ifndef _FRACTION_H_
#define _FRACTION_H_
using namespace std;
class Fraction
{
public:
Fraction();
Fraction(int n, int d);
int getNumerator() const;
int getDenominator() const;
void display();
string to_string();
Fraction operator+(Fraction &second);
private:
int numerator;
int denominator;
};
这是我的.cpp文件:
#include "Fraction.h"
#include <string>
include <iostream>
using namespace std;
Fraction::Fraction(){}
Fraction::Fraction(int n, int d)
{
this->numerator = n;
this->denominator = d;
}
int Fraction::getNumerator() const
{
return numerator;
}
int Fraction::getDenominator() const
{
return denominator;
}
Fraction Fraction::operator+(Fraction &second)
{
int n1 = getNumerator() * second.getDenominator();
int n2 = second.getNumerator() * getDenominator();
int d = getDenominator() * second.getDenominator();
return Fraction(n1+n2, d);
}
string Fraction::to_string()
{
return (getNumerator() + "/" + getDenominator()) ;
}
这是我的主要方法:
bool get_input(Fraction &fract);
int main()
{
Fraction fraction1, fraction2;
if (((!get_input(fraction1)) || (!get_input(fraction2))))
cout << "Invalid Input!" << endl;
else
{
// Test harness for Arithmetic Operator Overloading
Fraction result = fraction1 + fraction2;
cout << "Addition = " << result.to_string() << endl;
}
bool get_input(Fraction& fract)
{
int num, den;
cout << "Enter numerator & denominator (separated by space)" << endl;
cin >> num >> den;
if (cin.fail())
return false;
Fraction f(num,den);
fract = f;
return true;
}
}
它设法接受用户输入。但是,它不会打印出结果。提前致谢。