+ 10
How to create a typecast operator for a class?
I have a complex class: https://code.sololearn.com/cBtitZp78PHp/?ref=app I now wish to do the following: cout<<Complex(4,4); But, I get a lot of errors, like unable to bind rvalue reference as lvalue to ostream object, etc. How can I define a function to achieve the typecast we are able to do for integers and other fundamental data types? Please help!
33 ответов
+ 1
@Kinshuk
I think this is what you are looking for
https://code.sololearn.com/c82FZrifeo07/?ref=app
+ 10
... this is not what you want is it?
friend ostream& operator<<(ostream &output, Complex c) {
output << c.Re() << ", " << c.Im();
return output;
}
https://code.sololearn.com/cRhKLnJHWX2n/#cpp
+ 9
https://www.sololearn.com/discuss/501218/?ref=app
+ 8
Iff you are stuck you can always go bavk to the course and refer
+ 7
@jay
I have the ostream& operator << overload, and can do this:
Complex a(2,2);
cout<<a<<endl;
But I am unable to print like this:
cout<<Complex(4,4)<<endl;
while we can print like this:
cout<<int(32.5)<<endl;
+ 7
@jay
Lemme try...
Hmm, its printing 4,4 on CppDroid as well.
Guess there is still a problem with Code PlayGround...
+ 7
😀 when isnt there a problem!
edit: I will take down your code now from my profile
+ 7
@jay
Thank You very much!
Now, I wish to get the real 'typecast function', like: int a = int(22.22);
For my complex class...
How to create such a function so that,
Complex(2.33,'A') is saved as 2.33, 65 ?
+ 6
Works like that in the code I did. I couldnt find the overload you did. I will look again
edit: still can't see where you overloaded
+ 6
Dang.. this notification got lost..I will look see. Edit: I think that the easiest method without looking at the code again would be to create a template for complex. maybe
+ 6
you can set the pair to any data type.
int, float
dbl dbl
etc
+ 6
but yes. you could do the same with your functions
+ 6
i will demonstrate code when i get home
+ 6
https://code.sololearn.com/czpRM40uGsGN/?ref=app
edits in progress, but you get the idea.
+ 5
@jay
Yours is printing -0, -0 idk why...
The values, aren't being saved for use I think.
Mine has the following prototype, thats why there is an error:
friend ostream& operator << (ostream&, Complex&);
//Now rvalues can't be passed, can they?
+ 5
template <class aType, class aType2>
class Complex {
private:
aType real;
aType2 imag;
public:
Complex(aType re = 0, aType2 im = 0) :real(re), imag(im) {}
//etc etc
}
// in main
cout << Complex<int, char>(4, 'A');
+ 5
I think @Complex has the answer
+ 4
i know works on pc, but not here.. keeps asking for input too
+ 4
@Kinshuk. I do not know.. I changed my prototype to that of above and it still works on the pc..
well it outputs real, imaginary;
which is I assume is what you want
+ 4
@jay
That will make it more like a pair, wouldn't it?
I need something to perform explicit conversions from fundamental data types to complex...