Juscallmesteve Juscallmesteve - 1 year ago 82
C++ Question

Trouble with Classes and Functions more information inside

I am sorry but I am not even sure what this would be called to search for the question and answers.

I have a class Function

cout << "Fraction x, y(2), z(-5,-6), w(1,-3);" << endl;
Fraction x, y(2), z(-5,-6), w(1,-3);
//Initializing the Fraction class with X at default values
//Y with 2 as Numerator and default value, Z and W with their values.
cout << "z = " << z << ", y = " << y << ", z = " << z
<< ", w = " << w << endl;

My issue is how do I make the "cout << "z= " << z << endl; print out the fraction for z. How I have this made up is I could do z.output(); and it would print out the function perfectly but if I would to just put z I would get an error because neither the program nor I know how to make this work. I am hoping it is a very simple fix. I tried to assign z = z.output() but that is not working due to different value types. So I changed them both to the type Fraction and it still is not working.

I have to use that top program (main) as is and cannot modify it. I can only modify my own functions

Thank you

Answer Source

You can do this (this is a global function; not a method in any particular class):

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

I'm assuming that output() has a suitable return type. If not then you can always insert alternative code in the above function.

This is the idiomatic way: note that you return a reference to the passed stream to enable the chaining of <<.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download