首页 > 代码库 > 运算符重载例题

运算符重载例题

题目一:不用运算符重载,实现两个复数的相加。产生复数对象c1,c2,得到c3=c1+c2,并打印输出c3。

技术分享
#include <iostream>
using namespace std;
class complex
{
    public:
        complex(){real=0;imag=0;}
        complex(double r,double i):real(r),imag(i){}
        complex complex_add(complex & c2);
        void display();
    private:
        double real,imag;
};
complex complex::complex_add(complex & c2)
{
    complex c;
    c.real=real+c2.real;//谁调用就是谁的this
    c.imag=imag+c2.imag;
    return c;
}
void complex::display()
{
    cout<<"("<<real<<","<<imag<<")"<<endl;
}

int main()
{
    complex c1(3.5,4.5),c2(3.6,4.4),c3;
    c3=c1.complex_add(c2);
    c3.display();
    return 0;
}
View Code

运算符重载:

函数类型 operator 运算符名称(形参列表);
operator+运算符名称,可以理解为函数名

complex complex::operator+(complex &c2)
{  
return complex(real+c2.real,imag+c2.imag);  }

技术分享
#include <iostream>
using namespace std;
class complex
{
    public:
        complex(){real=0;imag=0;}
        complex(double r,double i):real(r),imag(i){}
        complex operator+(complex & c2);
        void display();
    private:
        double real,imag;
};
complex complex::operator+(complex & c2) //运算符重载
{
    return complex(real+c2.real,imag+c2.imag);
}
void complex::display() //输出
{
    cout<<"("<<real<<","<<imag<<")"<<endl;
}

int main()
{
    complex c2(3.6,4.4),c3;
    c3=complex(3.5,4.5)+c2;
    c3.display();
    return 0;
}
View Code

 

 

 

运算符重载例题