C ++重载+操作员友元函数

时间:2012-12-15 02:03:47

标签: c++ overloading

我正在尝试创建一个重载的友元函数,它将添加两个分数。到目前为止,我有以下解决方案,但我在第17行和第19行有错误。我认为问题在于参数(分数amount1,分数amount2),但我不能完全把手指放在它上面。有人可以帮忙吗?这需要在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;
}

然而,在测试时,我输出分子和分母变量的零。任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

这是在一系列变化之后编译的:

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

这个构造函数

fraction(); //constructor for initialize

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

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

friend fraction operator +(const fraction&, const fraction&)

答案 1 :(得分: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;
}

答案 2 :(得分:-1)

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

fraction fraction::operator +(fraction amount1, fraction amount2);