实现 Complex 的的二个版本 —— 重载四则混合运算。
#include <iostream>
using namespace std;
class Complex {
public:
Complex();
Complex(double, double);
Complex(const Complex&);
private:
double real;
double image;
public:
double getReal() const;
void setReal(double);
double getImage() const;
void setImage(double);
public:
/*************** begin *********************/
Complex operator+(const Complex& c);
Complex operator-(const Complex& c);
Complex operator*(const Complex& c);
Complex operator/(const Complex& c);
/*************** end *********************/
};
Complex::Complex() {
real = image = 0;
}
Complex::Complex(double r, double i) {
real = r;
image = i;
}
Complex::Complex(const Complex& c) {
real = c.real;
image = c.image;
}
double Complex::getReal() const {
return real;
}
void Complex::setReal(double r) {
real = r;
}
double Complex::getImage() const {
return image;
}
void Complex::setImage(double i) {
image = i;
}
/*************** begin *********************/
Complex Complex::operator+(const Complex& c)
{
return Complex(this->real + c.real, this->image + c.image);
}
Complex Complex::operator-(const Complex& c)
{
return Complex(this->real - c.real, this->image - c.image);
}
Complex Complex::operator*(const Complex& c)
{
double r = this->real * c.real - this->image * c.image;
double i = this->image + c.real + this->real * c.image;
return Complex(r, i);
}
Complex Complex::operator/(const Complex& c)
{
double r = (this->real * c.real + this->image * c.image) / (c.real * c.real + c.image * c.image);
double i = (this->image * c.real - this->real * c.image) / (c.real * c.real + c.image * c.image);
return Complex(r, i);
}
/*************** end *********************/
int main(int argc, char** argv) {
double real, image;
cin >> real >> image;
Complex c1(real, image);
cin >> real >> image;
Complex c2(real, image);
Complex c = c1 + c2;
cout << c.getReal() << endl;
cout << c.getImage() << endl;
return 0;
}