- 几种运算符重载
- 输入输出重载
- 加减乘除自加自减
- ++ - -,前缀++ - -
- 对下标运算符重载
- 对强制类型转换重载
#include<iostream>
#include<string>
#include<cmath>
using namespace std;
class Complex{
public:
Complex(int _real = 0,int _imag = 0){
real = _real;
imag = _imag;
}
friend istream& operator>>(istream&,Complex&);
friend ostream& operator<<(ostream&, Complex&);
Complex operator+(const Complex &another);
Complex operator-(const Complex &another);
Complex operator*(const Complex &another);
Complex operator/(const Complex &another);
Complex operator++(int);
Complex& operator++();
Complex& operator--();
Complex operator--(int);
operator double();
void show(){
cout<<real<<"+"<<imag<<"i"<<endl;
}
private:
int real,imag;
};
class ComplexArray{
public:
friend istream& operator>>(istream&,ComplexArray&);
friend ostream& operator<<(ostream&,ComplexArray&);
Complex operator[](int index);
private:
int len;
Complex c[101];
};
Complex::operator double(){
return sqrt(real*real+imag*imag);
}
Complex ComplexArray::operator[](int index){
if(index<1||index>len) return Complex(0,0);
return c[index];
}
Complex& Complex::operator++(){
real++;
imag++;
return *this;
}
Complex& Complex::operator--(){
real--;
imag--;
return *this;
}
Complex Complex::operator++(int){
Complex sum;
sum.real = real;
sum.imag = imag;
real++;
imag++;
return sum;
}
Complex Complex::operator--(int){
Complex sum;
sum.real = real;
sum.imag = imag;
real--;
imag--;
return sum;
}
istream& operator>>(istream& is,ComplexArray& ca){
is>>ca.len;
for(int i=1;i<=ca.len;i++)
is>>ca.c[i];
}
ostream& operator<<(ostream& os, ComplexArray& ca){
os<<ca.len<<endl;
for(int i=1;i<=ca.len;i++)
os<<ca.c[i]<<endl;
}
istream& operator>>(istream& is,Complex& c){
is>>c.real>>c.imag;
return is;
}
ostream& operator<<(ostream& os, Complex& c){
cout<<c.real<<"+"<<c.imag<<"i";
return os;
}
Complex Complex::operator+(const Complex &another){
Complex sum;
sum.real=real+another.real;
sum.imag=imag+another.imag;
return sum;
}
Complex Complex::operator-(const Complex &another){
Complex sum;
sum.real=real-another.real;
sum.imag=imag-another.imag;
return sum;
}
Complex Complex::operator*(const Complex &another){
Complex sum;
sum.real=real*another.real-(imag*another.imag);
sum.imag=imag*another.real+real*another.imag;
return sum;
}
Complex Complex::operator/(const Complex &another){
Complex sum;
sum.real=(real*another.real+imag*another.imag)/(another.imag*another.imag+another.real*another.real);
sum.imag=(imag*another.real-real*another.imag)/(another.imag*another.imag+another.real*another.real);
return sum;
}
int main()
{
ComplexArray c;
Complex b;
cin>>c;
b = c[3];
cout<<(double)b;
return 0;
}