当前位置:   article > 正文

用c++实现复数类的基本运算_c++定义一个复数类的加法减法

c++定义一个复数类的加法减法

程序的要求

定义一个复数类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>>将提示用户输入实部和虚部。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

程序的代码

#头文件

#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 << "2
c is" << 2
c << endl;
cout << “Enter a complex number(q to quit):” << endl;
}
cout << “Done!” << endl;
return 0;
}

程序的运行结果

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/818533
推荐阅读
相关标签
  

闽ICP备14008679号