运算符的重载

来源:互联网 发布:oracle数据库rowid 编辑:程序博客网 时间:2024/05/19 14:51

运算符的重载:为了赋予运算符新的含义,以扩展运算符的功能

有的运算符只能在类的成员函数中实现,有的只能在类的外部实现

示例程序:

#include "stdafx.h"
#include <iostream>
using namespace std;

class Complex
{
private:
double real;
double vir;
public:
Complex(){real = 10;vir = 3;}
Complex(int a,int b){real = a;vir = b;}
Complex operator+(Complex &b);                               //+,-,* ,/  运算符既可以在类的成员函数中实现,也
Complex operator-(Complex &b);                                              可以在类的外部实现
Complex operator*(Complex &b);
Complex operator/(Complex &b);

        Complex &operator=(Complex &b);                            //-> ,  = ,  [] , () 运算符只能在类的成员函数中实现

void operator()(int a,int b,char *c);
void setreal(double m_real){real = m_real;}
double getreal(){return real;}
void setvir(double m_vir){vir = m_vir;}
double getvir(){return vir;}
        friend ostream & operator<<(ostream & on, Complex &b);               //  << , >> 插入,提取运算符只能在
friend istream & operator>>(istream & in, Complex &b);                                    类的外部实现
};

ostream & operator<<(ostream & on, Complex &b)
{
cout<<"输出流被重载"<<"  "<<b.real<<"  "<<b.vir<<endl;
return cout;
}
istream & operator>>(istream & in, Complex &b)
{
cin>>b.real>>b.vir;
return cin;
}
Complex &Complex::operator=(Complex &b)
{
this->real= b.getreal();
this->vir = b->getvir();
cout<<"赋值运算符被重载"<<endl;
return *this;
}
void Complex::operator()(int a,int b,char *c)
{
cout<<"()被重载了"<<endl;
}
Complex* Complex::operator->()
{
cout<<"自定义箭头"<<endl;
return this;
}
Complex Complex::operator+(Complex &b)
{
Complex c;
    c.setreal(real +b.getreal());
c.setvir(vir+b.getvir());
return c;
}
Complex Complex::operator-(Complex &b)
{
Complex c;
c.setreal(real -b.getreal());
c.setvir(vir-b.getvir());
return c;
}
Complex Complex::operator*(Complex &b)
{
Complex c;
c.setreal(real *b.getreal());
c.setvir(vir*b.getvir());
return c;
}
Complex Complex::operator/(Complex &b)
{
Complex c;
c.setreal(real /b.getreal());
c.setvir(vir/b.getvir());
return c;
}
int _tmain(int argc, _TCHAR* argv[])
{
Complex d;
cin>>d;
cout<<d;
Complex a,b,c;
c = (a+b);
cout<<c.getreal()<<"\n"<<c.getvir()<<endl;
        c = a-b;
cout<<c.getreal()<<"\n"<<c.getvir()<<endl;
c = a*b;
cout<<c.getreal()<<"\n"<<c.getvir()<<endl;
c = a/b;
cout<<c.getreal()<<"\n"<<c.getvir()<<endl;
cout<<c->getreal()<<"\n"<<c->getvir()<<endl;
c(1,2,"aa");
return 0;
}