The following is the C++ codes for complex number for int data type. Please revi
ID: 3628470 • Letter: T
Question
The following is the C++ codes for complex number for int data type. Please revise the codes to create template for complex class to make the main program work.class Complex {
public:
Complex (int = 0 , int = 0 ); // constructor
Complex operator+( const Complex& ) const; // addition
void print();
private:
int real; // real part
int imaginary; // imaginary part
};
// Constructor
Complex::Complex(int r, int i )
{
real = r;
imaginary = i;
}
// Overloaded addition operator
Complex Complex::operator+( const Complex &operand2 ) const
{
Complex sum;
sum.real = real + operand2.real;
sum.imaginary = imaginary + operand2.imaginary;
return sum;
}
void Complex::print()
{
cout << real << " + " << imaginary << 'i' << endl;
}
//Use the following main function to test your program
int main() {
Complex<double> x, y( 4.3, 8.2 ), z( 3.3, 1.1 );
x = y + z;
x.print();
Complex<int> a, b( 4, 8 ), c( 3, 2 );
a = b + c;
a.print();
return 0; }
Explanation / Answer
please rate - thanks
#include <iostream>
using namespace std;
template <class T>
class Complex {
public:
Complex (T = 0 , T = 0 ); // constructor
Complex operator+( const Complex& ) const; // addition
void print();
private:
T real; // real part
T imaginary; // imaginary part
};
// Constructor
template <class T>
Complex<T>::Complex(T r, T i )
{
real = r;
imaginary = i;
}
// Overloaded addition operator
template <class T>
Complex<T> Complex<T>::operator+( const Complex &operand2 ) const
{
Complex sum;
sum.real = real + operand2.real;
sum.imaginary = imaginary + operand2.imaginary;
return sum;
}
template <class T>
void Complex<T>::print()
{
cout << real << " + " << imaginary << 'i' << endl;
}
//Use the following main function to test your program
int main() {
Complex<double> x, y( 4.3, 8.2 ), z( 3.3, 1.1 );
x = y + z;
x.print();
Complex<int> a, b( 4, 8 ), c( 3, 2 );
a = b + c;
a.print();
return 0; }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.