I'm trying to build a class complex
,
and in the method conjugate
I want the return statement to return the same object as the local variable res
and not a copy of it.
#include <iostream>
#include <math.h>
using namespace std;
class complex
{
float x, y;
public:
complex(float x, float y);
complex(float x) :complex(x, 0){}
complex() :complex(0, 0){}
complex(const complex &z) : complex(z.x, z.y) {}
~complex();
complex &conjugate();
friend ostream& operator<<(ostream&, const complex&);
};
ostream& operator<<(ostream& out, const complex& z){
out << z.x << "+" << z.y << "i";
return out;
}
complex::complex(float x, float y){
cout << "complex number created.\n";
this->x = x;
this->y = y;
}
complex &complex::conjugate(){
complex res;
res.x = this->x;
res.y = -this->y;
cout << "res val: " << res << endl;
cout << "res addr: " << &res << endl;
return res;
}
int main(){
complex a(1, 2);
complex* c = &(a.conjugate());
cout << "c val= " << *c << endl;
cout << "c addr= " << c << endl;
getchar();
return 0;
}
Output:
complex number created.
complex number created.
res val: 1+-2i
res addr: 002CFA0C
c val: -1.07374e+008+-1.07374e+008i
c addr: 002CFA0C
*c
and the local variable res
have the same address but not the same value.
Could anyone explain to me why?