?? 2.cpp
字號:
/*
Please improve the class complex of the PPT by
adding new operators like -, -=, *=,/=, and ++.
Then test those overloaded functions in the main function.
The operator overloaded functions should be defined as
member functions or as friend functions.
*/
#include <iostream.h>
class complex
{
public:
complex(double r=0,double i=0);
complex operator -();
complex operator +(const complex& c);
complex operator -(const complex& c);
complex operator *(const complex& c);
complex operator /(const complex& c);
complex operator ++();//prefix
complex operator ++(int);//postfix
void print() const;// const member function
private:
double real,imag;
};
complex::complex(double r,double i)
:real(r),imag(i){}
complex complex::operator -()
{
return complex(-real,-imag);
}
complex complex::operator +(const complex& c)
{
double r=real+c.real;
double i=imag+c.imag;
return complex(r,i);
}
complex complex::operator -(const complex& c)
{
double r=real-c.real;
double i=imag-c.imag;
return complex(r,i);
}
complex complex::operator *(const complex& c)
{
double r=real*c.real-imag*c.imag;
double i=imag*c.real+real*c.imag;
return complex(r,i);
}
complex complex::operator /(const complex& c)
{
double r=(real*c.real+imag*c.imag)/(c.real*c.real+c.imag*c.imag);
double i=(imag*c.real-real*c.imag)/(c.real*c.real+c.imag*c.imag);
return complex(r,i);
}
complex complex::operator ++()//prefix
{
real++;
imag++;
return complex(real,imag);
}
complex complex::operator ++(int)//postfix
{
real--;
imag--;
return complex(real,imag);
}
void complex::print() const
{
cout<<"("<<real<<","<<imag<<")"<<endl;
}
void main()
{
complex c1(2.5,3.7),c2(4.2,6.5);
complex c;
cout<<"c1為:\n";
c1.print();
cout<<"c2為:\n";
c2.print();
c=-c1;
cout<<"c1的相反數為:\n";
c.print();
c=-c2;
cout<<"c2的相反數為:\n";
c.print();
cout<<"c1-c2為:\n";
c=c1-c2;
c.print();
c=c1+c2;
cout<<"c1+c2為:\n";
c.print();
c=c1*c2;
cout<<"c1*c2為:\n";
c.print();
c=c1/c2;
cout<<"c1/c2為:\n";
c.print();
c=c2++;
cout<<"c2++為:\n";
c.print();
c=++c2;
cout<<"++c2為:\n";
c.print();
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -