Originally Posted by
843
Sorry, I don't quite understand what you mean. Would you mind showing an example?
Use the default argument in the class definition
Code:
class complexClass {
double x, y;
public:
complexClass(double r = 0, double i = 0);
and not in the function definition
Code:
complexClass::complexClass(double r, double i) : x(r), y(r)
{}
If you inline the constructor, do it this way.
Code:
class complexClass {
double x, y;
public:
complexClass(double r = 0, double i = 0) : x(r), y(r) {};
and obviously don't have a second not-inline definition.
Originally Posted by
843
Please help! There is something wrong with calculation of y. It keeps returning NaN.
Your copy constructor is not copying the value of y. Since your operator=() and operator+() functions accept arguments by value, the copy constructor is invoked whenever they are called. It will also possibly invoked when the functions return (although the compiler is allowed to avoid invoking the copy constructor in that case, it might invoke it anyway).
As Elysia said, either implement the copy constructor correctly, or don't implement it at all. (If you don't implement it, the compiler will, and the compiler-supplied default will work in this case).
Also note that,
1) If you don't need to implement a copy constructor, you usually don't need to implement an assignment operator (operator=()).
2) If you do need to implement operator=() or operator+() is is usually better if they accept arguments by const reference (in your case "const complexClass &"), not by value.