[YTU]_2441( C++习题 复数类--重载运算符2+)
生活随笔
收集整理的這篇文章主要介紹了
[YTU]_2441( C++习题 复数类--重载运算符2+)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
定義一個復數類Complex,重載運算符“+”,使之能用于復數的加法運算。參加運算的兩個運算量可以都是類對象,也可以其中有一個是整數,順序任意。例如,c1+c2,i+c1,c1+i均合法(設i為整數,c1,c2為復數)。編寫程序,分別求兩個復數之和、整數和復數之和。
輸入
兩個復數
一個復數和一個整數
一個整數和一個復數
輸出
兩個復數之和、復數和整數之和,整數和復數之和。
樣例輸入
3 4 5 -10 3 4 5 5 3 4樣例輸出
c1+c2=(8.00,-6.00i) c1+i=(8.00,4.00i) i+c1=(8.00,4.00i)#include <iostream> #include <iomanip> using namespace std; class Complex { public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}Complex operator+(Complex &c2);Complex operator+(int &i);friend Complex operator+(int&,Complex &);void display(); private:double real;double imag; }; Complex Complex:: operator+(Complex &c2) {return Complex(real+c2.real,imag+c2.imag); } Complex Complex::operator+(int &i) {return Complex(real+i,imag); } Complex operator+(int &i,Complex &c2) {return Complex(i+c2.real,c2.imag); } void Complex::display() {cout<<"("<<real<<','<<imag<<"i)"<<endl; } int main() {double real,imag;cin>>real>>imag;Complex c1(real,imag);cin>>real>>imag;Complex c2(real,imag);cout<<setiosflags(ios::fixed);cout<<setprecision(2);Complex c3=c1+c2;cout<<"c1+c2=";c3.display();int i;cin>>real>>imag;cin>>i;c3=Complex(real,imag)+i;cout<<"c1+i=";c3.display();cin>>i;cin>>real>>imag;c1=Complex(real,imag);c3=i+c1;cout<<"i+c1=";c3.display();return 0; }總結
以上是生活随笔為你收集整理的[YTU]_2441( C++习题 复数类--重载运算符2+)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [YTU]_2439( C++习题 复数
- 下一篇: [YTU]_2443 ( C++习题 复