-3

In short, i made class Fraction:

class Fraction
{
    int N;
    int D;
public:
    ostream& operator <<(ostream &);
    operator float();
};

and in function main() i have:

Fraction a(3, 4);
cout << a << " = " << endl;
cout << (float)a << endl;

as output i get:

0.750000 = 0.750000

Why operator << is unused ( it should print "( 3/4 )" ).

My operator << working correctly if i delete operator float, but i need conversion Fraction to float for some other methods and functions. How can i use my output operator.

Wanted output:

( 3/4 ) = 0.750000
user3464829
  • 69
  • 1
  • 9

3 Answers3

1

Implement operator << outside of your class, as a non-member (friend) function.

See Operator overloading.

Community
  • 1
  • 1
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

Your output operator<< should accept the stream as the first argument, and the fraction as the second argument. Right now, it does the opposite (the fraction is the first argument, and the stream is the second). This means the operator isn't called, instead the fraction is converted to float and then the float is displayed.

The operator you wrote can be called with a << cout, which is obviously wrong.

Instead of making it the member operator, you should implement this operator as (friend) non-member, outside of your class.

Sample signature:

std::ostream& operator<<(std::ostream& os, const Fraction& f);

milleniumbug
  • 15,379
  • 3
  • 47
  • 71
  • Made operator << as friend of class and it working now. I overloaded operator-() now, (1 argument "-"), it changes fraction to the opposite (3/4) -> (-3/4) cout << -a << endl; as output i get -0.750000 Why now it isn't (-3/4), ( my operator-() returns fraction ), i tried overload operator<< on different ways, also tried make operator-() as friend. – user3464829 Dec 26 '14 at 09:06
  • @user3464829 I cannot answer this question by only the details you posted. You should post more details (the best you can do is to strip the code to the base essentials (max 40 lines), so I can simply paste it in my IDE and compile), but... you may be better off with asking another question. – milleniumbug Dec 26 '14 at 12:06
  • As @πάντα ῥεῖ said, i made operator<< like this `friend ostream& operator <<(ostream &, const Fraction&);` (i miss "const") and now everything work correctly. – user3464829 Dec 26 '14 at 13:22
0

The operator<< should not be a member of your class, since it needs to have the stream object as its first argument and have signature ostream &operator<<(ostream &, Fraction).