我正在尝试创建一个重载的朋友函数,它将添加两个分数。到目前为止,我有以下解决方案,但我在第 17 行和第 19 行有错误。我相信问题出在参数(分数数量 1,分数数量 2)上,但我无法完全确定它。任何人都可以帮忙吗?这需要在 Visual Studio 2010 上编译。
#include <iostream>
using namespace std;
class fraction
{
public:
fraction(); //constructor for initialize
void read(); //read 3 int from keyboard for the fraction
void print(); //print the fraction on screen
friend fraction operator +(fraction, fraction); //fraction add
private:
int integral, numerator, denominator;
}
int main(){
return 0;
}
fraction operator +(fraction amount1, fraction amount2)
{
fraction temp;
temp.integral = amount1.integral + amount2.integral;
temp.numerator = amount1.numerator + amount2.numerator;
temp.denominator = amount1.denominator + amount2.denominator;
return temp;
}
void fraction::read()
{
cin >> integral >> numerator >> denominator;
}
编辑:我已将我的加法算法更正为
friend fraction operator +(const fraction&, const fraction&); //fraction add
和
fraction operator +(const fraction& amount1, const fraction& amount2)
{
fraction temp;
temp.integral = amount1.integral + amount2.integral;
temp.numerator = (amount1.numerator)*(amount2.denominator) + (amount2.numerator)*(amount1.denominator);
temp.denominator = (amount1.denominator)*(amount2.denominator);
return temp;
}
然而,在测试这一点时,我为分子和分母变量输出零。有人能帮忙吗?