Hi all there.
I was given the task to write a simple Complex Number class as an exercise for a class I'm taking. I already met my professor and all went well (:)) but I'm left with a question which I forgot to ask her: how should I handle any attempt of division by zero?
So far I managed an - ugly - solution: I declared a static bool variable for the class and set it to false. Then, at any time a division by zero is about to occurr all my class would do is return/process 0+0i as the result and set static bool div_by_zero_attempted to true. Then, in the destructor, I check its state and eventually print on screen an error message which tells that the results given by the program are not reliable. After that I reset the variable to false (just to avoid multiple error messages as long as one is enough for my purpose).
I am providing an extract from my code (the operator/ and the destructor) and I'm asking to you: is there a better/standard way to handle such cases?
Here's the code, anticipated thanks for any reply :)
Complex Complex::operator/(Complex op2) {
Complex temp;
if(op2.Real==0&&op2.Imaginary==0) {
temp.Real = 0;
temp.Imaginary = 0;
Complex::div_by_zero_attempted = true;
}
else {
temp.Real = (Real*op2.Real) + (Imaginary*op2.Imaginary);
temp.Imaginary = (op2.Real*Imaginary) - (Real*op2.Imaginary);
temp = temp/(op2.Modulus()*op2.Modulus());
}
return temp;
}
Complex::~Complex(void) {
if(div_by_zero_attempted) {
std::cout << std::endl << "The programm tried to process a division by zero. Any results should not be trusted." << std::endl;
div_by_zero_attempted = false;
}
}