I need help on this C++ operator overloading activity. Thank you Consider the fo
ID: 3754818 • Letter: I
Question
I need help on this C++ operator overloading activity. Thank you
Consider the following class definition to define a class for complex numbers:
class Complex
{
private:
double real;
double imaginary;
public:
Complex(double r = 0, double i = 0) {real = r; imaginary = i;}
};
and the following main() function:
int main()
{
Complex X, Y, Z;
cout << "Enter two complex numbers (in the form 7.1+8.3i): ";
cin >> X;
cin >> Y;
Z = X + Y;
cout << X << " + " << Y << " = " << Z << endl;
Z = X - Y;
cout << X << " - " << Y << " = " << Z << endl;
cout << X << " as a double is " << (double)X << endl;
system("pause");
return 0;
}
Create a new Visual Studio project with files complex.h, complex.cpp, and main.cpp. Write the code that would be necessary to get this program to compile and work correctly (i.e. you should overload the appropriate operators for the Complex class).
Explanation / Answer
#include #include using namespace std; class Complex { private: double real; double imaginary; public: Complex(double r = 0, double i = 0) { real = r; imaginary = i; } Complex &operator-(const Complex &c) { Complex *result = new Complex(real - c.real, imaginary - c.imaginary); return *result; } Complex &operator+(const Complex &c) { Complex *result = new Complex(real + c.real, imaginary + c.imaginary); return *result; } operator double() { return sqrt(real*real + imaginary*imaginary); } friend ostream &operator(istream &in, Complex &c); }; ostream &operator X; cin >> Y; Z = X + Y; coutRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.