C++ 11 Complex Class Program I\'m having trouble understanding how to write the
ID: 3767000 • Letter: C
Question
C++ 11 Complex Class Program
I'm having trouble understanding how to write the code for the following question:
Create a class called Complex for performing arithmetic with complex numbers. Write a program to test the class. Recall that complex numbers have the form realPart + imaginaryPart x i, where i is the square root of -1.
Use double variables to represent the private data of the class. Provide a constructor that enables an object of this class to be initialized when it's declared. The constructor should contain default values in case no initializers are provided. Provide public member functions that perform the following tasks:
a. Adding two Complex numbers: The real parts are added together and the imaginary parts are added together.
b. Subtracting two complex numbers: The real part of the right operand is subtracted from the real part of the left operand, and the imaginary part of the right operand is subtracted from the imaginary part of the left operand.
c. Printing Complex numbers: Print complex numbers in the form (a,b), where a is the real part and b is the imaginary part.
(For reference: The above question is 9.5 from page 428 of C++ How to Program 9th Edition, Author:Paul Deitel)
If someone could provide an example of code that would fulfill the above question, that would be great.
Furthermore, is there an intuitive way to separate the code into a header file and two .cpp files?
Thank you for your help.
Explanation / Answer
#include <iostream.h>
class Complex {
public:
double pr; //for real part
double pi; //for imaginary part
public:
void add(Complex, Complex);
void subtract(Complex, Complex);
void print();
};
void Complex::add (Complex op1, Complex op2) {
pr = op1.pr + op2.pr;
pi = op1.pi + op2.pi;
}
void Complex::subtract (Complex op1, Complex op2) {
pr = op1.pr - op2.pr;
pi = op1.pi - op2.pi;
}
void Complex::print () {
cout << "("<<r<<", " << pi <<")";
}
void main () {
Complex operand1, operand2, result;
cout << " enter real part for operand one: " << endl;
cin >> operand1.pr;
cout << "enter imaginary part for operand one: " << endl;
cin >> operand1.pi;
cout << "enter real part for operand two: " << endl;
cin >> operand2.pr;
cout << "enter imaginary part for operand two: " << endl;
cin >> operand2.pi;
cout << " The sum is ";
result.add(operand1, operand2);
result.print();
cout << " The difference is ";
result.subtract(operand1, operand2);
result.print();
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.