I started so study OOP in C++ and I have some issue with an exercise.
I have to create a class "Complex" with a method equal()which checks if 2 complex numbers are equal.This method will have the following prototype: int Complex::equal(Complex c2);. The method will compare the complex numbers "this" and "c2" and will return 1 if this == c2 and 0 if it's not equal.
Also, I need to write a method Complex::read() which reads the complex number from keyboard.
In the end, I have to write a program which reads 2 complex numbers and show the result of their comparison.
#pragma once
#include <iostream>
usingnamespace std;
class Complex {
int re, im; // re = real part of complex number and im = imaginary part of complex number
public:
Complex() {
re = im = 0;
}
Complex(int re, int im) {
this->re = re;
this->im = im;
}
void display() {
cout << "( " << re << ", " << im << " )" << endl;
}
int equal(Complex c2);
void read();
};
You need two distinct Complex objects to exist at once so that you can compare them with equals. Instead of the loop in your main, have something like:
Thank you for the answer.
So because I'm calling the function equal again, I deleted the "reading input" from equal method.
Now my methods file looks like this:
#include "complex.h"
#include <iostream>
usingnamespace std;
int main() {
int n = 0;
Complex c1(10, 5);
Complex c2;
c2.read();
int ok = c1.equal(c2);
if (ok) {
cout << "The complex numbers are equal" << endl;
}
else {
cout << "The complex numbers are not equal" << endl;
}
cout << "Enter 2 complex numbers: " << endl;
Complex num1;
Complex num2;
num1.read();
num2.read();
cout << "Equal? " << num1.equal(num2) << '\n';
system("pause");
return 0;
}
But I still get wrong answers. For the first part I get "not equal" even if I enter 10 for real part and 5 for imaginary part.
For the second part with those 2 numbers I get true for any values I enter.
I think the "read" method is wrong. How to fix this?
Thanks!
This function is creating a Complex object called 'number', and using cin to assign its real/imaginary parts. But this object called 'number' has nothing to do with your actual object's re/im members.
You want to be assigning to this->re and this->im instead.