从int类型的rvalue初始化类型& Fraction的非const引用?

时间:2014-11-30 14:47:15

标签: c++ pointers error-handling

#include <iostream>
#include <utility>
using namespace std;
using namespace rel_ops;

class Fraction
{

private:
  //variables to store numerator and denominator
  int num;
  int denom;

public:
  Fraction(){}
  Fraction(int num): num(num) {}
  Fraction(int num, int denom): num(num), denom(denom) {}

  void set_num(int n){ num = n;}
  void set_denom(int d){ denom = d;}

  int get_numerator() const {return num;}
  int get_denominator() const {return denom;}

  Fraction &operator+= (const Fraction &obj){
    if (denom == obj.denom){
      return num + obj.num;
    }
  }
};

  //calculating highest common denominator
  int g_c_d(int n, int d){
    return d == 0? n : g_c_d(d, n % d);
 }

istream &operator>> (istream &input, Fraction &f)
{
  int n, d;
  char slash;
  input >> n;
  input >> slash;
  input >> d;

  if (d == 0) {n = 0;} //if denom is 0; fraction = 0/0
  f = Fraction(n, d);
  return input;
}

ostream &operator<<(ostream &output, const Fraction &frac)
{
  return output << frac.get_numerator() << "/" << frac.get_denominator();
}


int main()
{
   int n, d;
   Fraction frac;
   Fraction frac1(3,4);
   Fraction frac2(4,4);

   cout << frac1 << " + " << frac2 << " = ";
   cout << (frac1 += frac2) << endl;

   cout << "Enter a fraction" << endl;
   cin >> frac;  //user inputs fraction      
   n = frac.get_numerator();  //get users numerator
   d = frac.get_denominator();  //get users denominator
   gcd = g_c_d(frac.get_numerator() , frac.get_denominator());  //calculate gcd of     fraction using users input

   //set new simplified values for the users fraction
   frac.set_num(n/gcd);
   frac.set_denom(d/gcd);
   cout << "your fraction is: ";
   cout << frac << endl;

   return 0;
}

我正在尝试添加两个分数,这些分数来自我自己定义的类。但是我收到此错误: 从类型的右值开始,类型&amp; Fraction的非const引用的初始化无效。

我重载了其他运营商,例如&#34; ==&#34;它工作正常,但&#34; + =&#34;不起作用。

1 个答案:

答案 0 :(得分:3)

你的operator +=返回一个临时的,应该是这样的:

Fraction &operator+= (const Fraction &obj){
   if (denom == obj.denom){
      num += obj.num;
    } else {
        // you have also to do that part
    }
    return *this; // return this object, not a temporary
}