Question:
Write a class for complex numbers. A complex number has the form a + b i a+bi a+bi, where a a a and b b b are real numbers and i i i is the square root of − 1 -1 −1. We refer to a a a as the real part and b b b as the imaginary part of the number. The class should have two data members to represent the real and imaginary numbers; the constructor takes two arguments to set these numbers. Discuss and implement other appropriate operators for this class.
My answer:
complex.h
#pragma once
class complex{
public:
complex(){real = imagine = 0;};
complex(double a, double b){
real = a;
imagine = b;
};
// double get_real();
// double get_imagine();
void print_info();
friend complex operator +(const complex &a, const complex &b);
friend complex operator -(const complex &a, const complex &b);
friend complex operator *(const complex &a, const complex &b);
friend complex operator /(const complex &a, const complex &b);
private:
double real;
double imagine;
};
complex.cpp
#include "complex.h"
#include <iostream>
#include <cassert>
#include <cmath>
using namespace std;
void complex::print_info(){
if(real == 0 && imagine != 0){
cout << imagine << "i" << endl;
return;
} else if(real == 0 && imagine == 0){
cout << "0" << endl;
return;
}
// 到这里real不为0
cout << real;
if(imagine > 0 && imagine != 1){
cout << "+" << imagine << "i" << endl;
} else if(imagine == 1){
cout << "+i" << endl;
} else if(imagine < 0 && imagine != -1){
cout << imagine << "i" << endl;
} else if(imagine == -1){
cout << "-i" << endl;
} else {// imagine == 0
cout << endl;
}
return;
}
complex operator +(const complex &a, const complex &b){
double n = a.real + b.real;
double m = a.imagine + b.imagine;
return complex(n, m);
}
complex operator -(const complex &a, const complex &b){
double n = a.real - b.real;
double m = a.imagine - b.imagine;
return complex(n, m);
}
complex operator *(const complex &a, const complex &b){
double n = a.real*b.real - a.imagine*b.imagine;
double m = a.real*b.imagine + a.imagine*b.real;
return complex(n, m);
}
complex operator /(const complex &a, const complex &b){
assert(!(b.real == 0 && b.real == 0));
double n = (a.real*b.real+a.imagine*b.imagine)/(pow(b.real, 2)+pow(b.imagine, 2));
double m = (a.imagine*b.real-a.real*b.imagine)/(pow(b.real, 2)+pow(b.imagine, 2));
return complex(n, m);
}
main.cpp
#include "complex.h"
#include <iostream>
using namespace std;
int main(){
complex a = complex(7, 1);// 7+i
complex b = complex(3, 4);// 3+4i
complex c;
cout << "a = ";
a.print_info();
cout << "b = ";
b.print_info();
cout << "c = a + b = ";
c = a + b;
c.print_info();
cout << "c = a - b = ";
c = a - b;
c.print_info();
cout << "c = a * b = ";
c = a * b;
c.print_info();
cout << "c = a / b = ";
c = a / b;
c.print_info();
return 0;
}
结果:
a = 7+i
b = 3+4i
c = a + b = 10+5i
c = a - b = 4-3i
c = a * b = 17+31i
c = a / b = 1-i
Reference:
整理自 Data Structures and Other Objects Using C++ ( Fourth Edition ) Michael Main, Walter Savitch. p125