2

我正在尝试创建一个重载的朋友函数,它将添加两个分数。到目前为止,我有以下解决方案,但我在第 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;
}

然而,在测试这一点时,我为分子和分母变量输出零。有人能帮忙吗?

4

3 回答 3

0

这是在经过多次更改后编译的:

  • 您需要在类定义后添加一个分号,并且
  • 您需要定义您已声明的构造函数,即

这个构造函数

fraction(); //constructor for initialize

应该有一个内联或在单独文件中定义的正文。

此外,您应该将您的签名更改operator

friend fraction operator +(const fraction&, const fraction&)
于 2012-12-15T02:38:36.597 回答
0
#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(){
fraction f1, f2, f3;
cout<<"\n Enter first fraction: ";
f1.read();
cout<<"\n Enter second fraction: ";
f2.read();
cout<<"\n result: ";

f3 = f1 + f2;
f3.print();
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;
}

void fraction::print()
{
cout << integral<<" "<< numerator <<" "<< denominator <<std::endl;
}
于 2016-10-14T08:02:03.800 回答
-1

如果在类块之外定义,则需要在运算符之前使用类名:

fraction fraction::operator +(fraction amount1, fraction amount2);
于 2012-12-15T02:06:35.037 回答