操作符重载

可重载的运算符列表:

双目算术运算符    + (加),-(减),*(乘),/(除),% (取模)
关系运算符    ==(等于),!= (不等于),< (小于),> (大于>,<=(小于等于),>=(大于等于)
逻辑运算符    ||(逻辑或),&&(逻辑与),!(逻辑非)
单目运算符    + (正),-(负),*(指针),&(取地址)
自增自减运算符    ++(自增),--(自减)
位运算符    | (按位或),& (按位与),~(按位取反),^(按位异或),,<< (左移),>>(右移)
赋值运算符    =, +=, -=, *=, /= , % = , &=, |=, ^=, <<=, >>=
空间申请与释放    new, delete, new[ ] , delete[]
其他运算符    ()(函数调用),->(成员访问),,(逗号),[](下标)

不可重载的运算符列表:

.:成员访问运算符
.*, ->*:成员指针访问运算符
:::域运算符
sizeof:长度运算符
?::条件运算符
#: 预处理符号

#include <iostream>
using namespace std;

class  Complex
{
    public:
        Complex(){
            lValue = 0;
            rValue = 0;
        }
        Complex(int a,int b):lValue(a),rValue(b){}
        /*Complex operator +(Complex a){return Complex(this->lValue + a.lValue,this->rValue + a.rValue);} 
        Complex operator -(Complex a){return Complex(this->lValue - a.lValue,this->rValue - a.rValue);} 
        Complex operator *(Complex a){return Complex(this->lValue * a.lValue,this->rValue * a.rValue);} 
        Complex operator /(Complex a){return Complex(this->lValue / a.lValue,this->rValue / a.rValue);} */
        Complex operator ++(int n){Complex p =*this;this->lValue++;this->rValue ++;return p;} //i++
        Complex operator ++(){this->lValue++;this->rValue ++;return *this;}                   //++i
        friend Complex operator +(Complex &b,Complex &a){return Complex(b.lValue + a.lValue,b.rValue + a.rValue);} 
        friend Complex operator -(Complex &b,Complex &a){return Complex(b.lValue - a.lValue,b.rValue - a.rValue);} 
        friend Complex operator *(Complex &b,Complex &a){return Complex(b.lValue * a.lValue,b.rValue * a.rValue);} 
        friend Complex operator /(Complex &b,Complex &a){return Complex(b.lValue / a.lValue,b.rValue / a.rValue);} 
        friend ostream & operator <<(ostream &output,const Complex &a)
        {
            output<<a.lValue<<" : "<<a.rValue<<endl;
            return output;
        }
        /*ostream & operator<<(ostream &output)
        {
            output<<this->lValue<<" : "<<this->rValue<<endl;
            return output;
        }*/
        double operator () (int a, int b)
        {
            return a*b*lValue*rValue;
        }

    private:
        int lValue;
        int rValue; 
};
int main()
{
    Complex a1(1,2);
    Complex a2(2,3);
    //a1<<cout; //member reload call
    cout<<a1;
    cout<<a2;
    cout<<a1+a2;
    cout<<a1-a2;
    cout<<a1*a2;
    cout<<a1/a2;
    cout<<a1++;
    cout<<++a2;
    cout<<a1(1,5);
    return 0;
}

output:

$ ./a.exe
1 : 2
2 : 3
3 : 5
-1 : -1
2 : 6
0 : 0
1 : 2
3 : 4
30

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值