Reputation: 824
Hey guys I have a problem with one of my methods (overriding an operator , ~ ) When I try to print my object, something unexpected happens... need some help
this is my whole code
#include"stdafx.h"
#include<iostream>
using namespace std;
class complex
{
private:
double Re, Im;
public:
complex(double _Re = 0, double _Im = 0) : Re(_Re), Im(_Im){} //class constructor
void print() const
{
cout << Re << " + " << "i(" << Im << ")" << endl;
}
complex operator~() const
{
return (Re, -Im);
}
};
void main()
{
complex x(2, 3);
x.print();
(~x).print();
}
If i compile it, I'll get the correct complex number on the screen, but when I try to execute the ~ overridden operator it displays to me - -3 + 0 i
....
Really need some help.
Thanks
Sorry for posting such brain-dead questions, but I can't figure it out by myself....been looking at the damn code for more than 30 minutes and I can't see where I am wrong.
Upvotes: 0
Views: 62
Reputation: 35418
Since you accept default values for your constructor (0
) the compiler takes the expression: return (Re, -Im);
evaluates Re
(it is 2) throws away and creates a new complex
with the -Im
by calling the constructor like: complex(-3, 0)
. So this is how you get the funny value.
Upvotes: 0
Reputation:
You are missing a complex(Re, -Im);
in:
complex operator~() const
{
return (Re, -Im);
}
Hence you return an implicit converted complex(-Im)
(comma operator).
You might use explicit constructors to avoid a pitfall like this.
Upvotes: 2
Reputation: 66932
return (Re, -Im);
This is using the comma operator, where it evaluates Re
(numbers do nothing), and then evaluates and "returns" -Im
(-3). Then, the return type is expected to be a complex
, so it tries to convert this -3 to a complex
. It finds this constructor: complex(double _Re = 0, double _Im = 0)
, and uses it: complex(-3, 0)
;
The immediate solution is to add the word complex
to the return
return complex(Re, -Im);
Or, in C++11, use {}
to tell the compiler that you meant to call the constructor:
return {Re, -Im};
Upvotes: 0
Reputation: 9618
The comma in
return (Re, -Im);
does NOT do what you think it does.
Surrounding something in parenthesis does NOT call a constructor. The parenthesis are discarded and the expression is evaluated as
return Re, -Im;
The comma means rvaluation each term and the result is the rightmost term.
Because the expression Re
doesn't do anything the expression is evaluated as
return -Im;
But this calls the constructor which has a default of 0 for the imaginary term. And so you get -3 for the real part and 0 for the imaginatry part.
Instead that line should read
return complex(Re, -Im);
Which constructs what you thought it should.
Upvotes: 0