c++: 复数类

mac2024-10-04  54

c++: 复数类

输出

#include<iostream> using namespace std; class complex { private: double real; double imaginary ; public: complex():real(0),imaginary(0){} complex(double x,double y):real(x),imaginary(y){} void operator = (const complex&c){ real=c.real; imaginary=c.imaginary; } ~complex(){} complex operator- () { return complex(-real,-imaginary); } complex operator+(const complex&c){ complex com; com.real=real+c.real; com.imaginary=imaginary+c.imaginary; return com; }// 定义复数加法 complex operator-(const complex&c){ complex com; com.real = real - c.real; com.imaginary = imaginary - c.imaginary; return com; }//定义复数减法 complex operator*(const complex&c){ complex com ; com.real = real*c.real - imaginary*c.imaginary; com.imaginary = real*c.imaginary + imaginary*c.real; return com; }// 定义复数除法 complex operator/(const complex&c){ complex com; double denominator = c.real*c.real + c.imaginary*c.imaginary; com.real = (real*c.real + imaginary*c.imaginary)/denominator; com.imaginary = (imaginary*c.real-real*c.imaginary)/denominator; return com; } /*习惯上人们是使用 cin>> 和 cout<< 的,得使用友元函数来重载运算符, 如果使用成员函数来重载会出现 d1<<cout; 这种不自然的代码*/ friend ostream &operator<<( ostream &output, const complex &c ){ output <<"( "<< c.real<<" ," <<c.imaginary<<" i )"; return output; }//输出运算符重载 friend istream &operator>>( istream &input, complex &c ){ input >> c.real >> c.imaginary; return input; }//输入运算符重载 }; int main(){ complex a(4,6),b(2,-1); cout<<a<<" + "<<b<<" = "<<a+b<<endl; cout<<a<<" - "<<b<<" = "<<a-b<<endl; cout<<a<<" * "<<b<<" = "<<a*b<<endl; cout<<a<<" / "<<b<<" = "<<a/b<<endl; return 0; }

输出

( 4 ,6 i ) + ( 2 ,-1 i ) = ( 6 ,5 i ) ( 4 ,6 i ) - ( 2 ,-1 i ) = ( 2 ,7 i ) ( 4 ,6 i ) * ( 2 ,-1 i ) = ( 14 ,8 i ) ( 4 ,6 i ) / ( 2 ,-1 i ) = ( 0.4 ,3.2 i )
最新回复(0)