overloaded fx error

Hi

I am trying to set up my non-member overloaded function for the following example and keep getting the following error from line 23:


 error: could not convert '{((& f2)->Fraction::getValNum() * (& f1)->Fraction::getValDenom())}' from '<brace-enclosed initializer list>' to 'Fraction'
   return{f2.getValNum() * f1.getValDenom()};


Source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>

class Fraction
{
	private:
		int numerator;
		int denomenator;
	public:
		Fraction(int numer, int denom){numerator = numer; denomenator = denom;};
		getValNum(){return numerator;};
		getValDenom(){return denomenator;};
		printVal()
		{
			int m_numer = getValNum();
			int m_denom = getValDenom();
			std::cout<<m_numer<<"/"<<m_denom<<std::endl;
		}
		friend Fraction operator * (Fraction &f1, Fraction &f2);
};

	Fraction operator*(Fraction &f2, Fraction &f1)
	{
		return{f2.getValNum() * f1.getValDenom()};
	}

int main()
{
Fraction f1 (2,5);
f1.printVal();

Fraction f2 (3,8);
f2.printVal();

//Fraction f3 = f1 * f2;
//f3.printVal();


return 0;
}


Once I get the error resolved I plan to further develop the code for multiplying the fractions.
closed account (iw7Gy60M)
The compiler doesn't know how to turn

{f2.getValNum() * f1.getValDenom()}

into an object of type Fraction (your function's return type). You need to do something like:

return Fraction(/* something */, /* something */);
You forgot to specify your return type for the two getters, as wells as the print function.

Also, how will multiplying the numerator of one fraction with the denominator of the other give you the correct answer? Shouldn't you multiply across (num*num and denom*denom) ?

Here's what that would look like:

1
2
3
4
Fraction operator*(Fraction &f2, Fraction &f1)
{    
    return Fraction(f2.getValNum() * f1.getValNum(), f2.getValDenom() * f1.getValDenom() ); // construct a Fraction object and return it
}


Only thing left is a function to reduce to simplest form. But I'll leave that to you.
Last edited on
Exactly it. Thx.
Some minor notes on style.

1) It's not necessary to use getters at lines 14-15. printval() has access to private member variables. Line 16 can simply be:
 
  std::cout << numerator << "/" << denominator << std::endl;

Using getters inside a class is slightly inefficient (it causes an unnecessary function call unless the function is inlined), and also makes your code more verbose (harder to read).

2) The same goes for your operator *
 
  return Fraction (f2.numerator * f1.numerator, f2.denominator * f1.denominator);


3) Lines 14-15: The "m_" prefix is conventionally used to indicate member variables. These are not member variables.
Topic archived. No new replies allowed.