赞
踩
定义一个复数类Complex,其类方法要实现如下的运算:
(1)加法:a+c=(A+C,(B+D)i);
(2)减法:a+c=(A-C,(B-D)i);
(3)乘法:a*c=(A*C-B*D,(A*D+B*C)i);
(4)数乘:x*c=(x*C,x*Di);
(5)共轭:~a=(A,-Bi);
(6)要求重载<<和>>运算符,重载>>运算符时,要求以(a,bi)的格式输出;重载>>运算符时,cin>>将提示用户输入实部和虚部。
#pragma once
#ifndef COMPLEX_H
#define COMPLEX_H
#include
class Complex {
private:
float Real;
float Imaginary;
public:
Complex();
Complex(float R, float I);
~Complex();
Complex operator+(const Complex& x) const;
Complex operator-(const Complex& x) const;
Complex operator*(const Complex& x) const;
Complex operator*( float x) const;
friend Complex operator*(float a, const Complex& x) ;
Complex operator~() ;
friend std::ostream& operator<<(std::ostream& os, const Complex& v);
friend std::istream& operator>>(std::istream& is, Complex& v);
};
#endif
#include
#include"complex0.h"
using namespace std;
Complex::Complex() {
Real = 0;
Imaginary = 0;
}
Complex::Complex(float R, float I) {
Real = R;
Imaginary = I;
}
Complex::~Complex() {
}
Complex Complex::operator+(const Complex& x) const {
return Complex(Real + x.Real, Imaginary + x.Imaginary);
}
Complex Complex::operator-(const Complex& x) const {
return Complex(Real - x.Real, Imaginary - x.Imaginary);
}
Complex Complex::operator*(const Complex& x) const {
return Complex(Realx.Real-Imaginaryx.Imaginary, Realx.Imaginary+Imaginaryx.Real);
}
Complex Complex::operator*(float x) const {
return Complex(Realx, Imaginaryx);
}
Complex operator*( float a, const Complex& x) {
return x * a;
}
Complex Complex::operator~() {
return Complex(Real, -Imaginary);
}
std::ostream& operator<<(std::ostream& os, const Complex& v) {
cout << “(” << v.Real << “,” << v.Imaginary << “i” << “)”;
return os;
}
std::istream& operator>>(std::istream& is, Complex& v) {
cout << “Real:”;
cin >> v.Real;
cout << “Imaginary:”;
cin >> v.Imaginary;
return is;
}
#include
#include"complex0.h"
using namespace std;
int main() {
Complex a(3.0, 4.0);
Complex c;
cout << “Enter a complex number(q to quit):” << endl;
while (cin >> c) {
cout << "c is " << c << endl;
cout << "complex conjugate is " << ~c << endl;
cout << "a is " << a << endl;
cout << “a+c is” << a + c << endl;
cout << “a-c is” << a -c << endl;
cout << "ac is" << a c << endl;
cout << "2c is" << 2c << endl;
cout << “Enter a complex number(q to quit):” << endl;
}
cout << “Done!” << endl;
return 0;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。