1-2.cpp

来自「平常学习c++的一些小程序」· C++ 代码 · 共 58 行

CPP
58
字号
/*
Please carefully review what we have learned about operator overloading, 
debug the programs from the PPT in the computer, and understand the mechanism of it.
*/

#include <iostream.h>
class complex
{
public:
    complex(double r=0,double i=0);
    friend complex operator +
        (const complex& c1,const complex& c2);
    friend complex operator -
        (const complex& c1,const complex& c2);
    friend complex operator -(const complex& c);
    void print() const;
private:
    double real,imag;
};
complex::complex(double r,double i)
{
    real=r;
    imag=i;
}
complex operator +(const complex& c1,
                                 const complex& c2)
{
    double r=c1.real+c2.real;
    double i=c1.imag+c2.imag;
    return complex(r,i);
}
complex operator -(const complex& c1,
                                const complex& c2)
{
    double r=c1.real-c2.real;
    double i=c1.imag-c2.imag;
    return complex(r,i);
}
complex operator -(const complex& c)
{
    return complex(-c.real,-c.imag);
}
void complex::print() const 
{
    cout<<"("<<real<<","<<imag<<")"<<endl;
}
void main()
{
    complex c1(2.5,3.7),c2(4.2,6.5);
    complex c;
    c=c1-c2;
    c.print();
    c=c1+c2;
    c.print();
    c=-c1;
    c.print();
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?