c++中运算符重载
一.前言
如上
二.內(nèi)容
題目:
定義一個復(fù)數(shù)類Complex,重載運算符“+”,“-”,“*”,“/”,使之能用于復(fù)數(shù)的加、減、乘、除。運算符重載函數(shù)作為Complex類的成員函數(shù)。編寫程序,分別求兩個復(fù)數(shù)之和、差、積和商。
三.代碼
#include<iostream> using namespace std; class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i):real(r),imag(i){}void display();//顯示復(fù)數(shù)Complex operator+(Complex &y);Complex operator-(Complex &y);Complex operator*(Complex &y);Complex operator/(Complex &y);private:double real;//實根 double imag;//虛根 }; void Complex::display() {//顯示復(fù)數(shù)cout<<"("<<real<<","<<imag<<"i)"; }Complex Complex:: operator+(Complex &y){//重載運算符+ return Complex(real+y.real,imag+y.imag); }Complex Complex:: operator-(Complex &y){//重載運算符-return Complex(real-y.real,imag-y.imag); }Complex Complex:: operator*(Complex &y){//重載運算符*Complex c;c.real=real*y.real-imag*y.imag;c.imag=real*y.imag +imag*y.real;return c; } Complex Complex:: operator/(Complex &y){//重載運算符/Complex c;double flag;//判斷標(biāo)志flag=y.real*y.real+y.imag*y.imag;c.real=(real*y.real+imag*y.imag)/flag;c.imag=(imag*y.real-real*y.imag)/flag; return c; } int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c1+c2=";c3.display() ;cout<<endl;c3=c1-c2;cout<<"c1-c2=";c3.display() ;cout<<endl;c3=c1*c2;cout<<"c1*c2=";c3.display() ;cout<<endl; c3=c1/c2;cout<<"c1/c2=";c3.display() ;cout<<endl; return 0; }總結(jié)
- 上一篇: 编译原理中中间代码生成---C语言实现
- 下一篇: numpy数据集