[YTU]_2439( C++习题 复数类--重载运算符+)
生活随笔
收集整理的這篇文章主要介紹了
[YTU]_2439( C++习题 复数类--重载运算符+)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
定義一個復數類Complex,重載運算符“+”,使之能用于復數的加法運算。將運算符函數重載為非成員、非友元的普通函數。編寫程序,求兩個復數之和。
輸入
兩個復數
輸出
復數之和
樣例輸入
3 4 5 -10樣例輸出
(8.00,-6.00i)#include <iostream> #include <iomanip> using namespace std; class Complex { public:Complex();Complex(double r,double i);double get_real();double get_imag();void display(); private:double real;double imag; }; Complex::Complex(){} Complex::Complex(double r,double i) {real=r;imag=i; } double Complex::get_real() {return real; } double Complex::get_imag() {return imag; } Complex operator + (Complex &c1,Complex &c2) {return Complex(c1.get_real()+c2.get_real(),c1.get_imag()+c2.get_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);Complex c3=c1+c2;cout<<setiosflags(ios::fixed);cout<<setprecision(2);c3.display();return 0; }總結
以上是生活随笔為你收集整理的[YTU]_2439( C++习题 复数类--重载运算符+)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [YTU]_2914 ( xiaopin
- 下一篇: [YTU]_2441( C++习题 复数