运算符重载 类 C++

/*
运算符重载
就是对已有的运算符(C ++中预定义的运算符)赋予多重的含义,
是同一个运算符作用与不同类型的数据是导致不同类型的行为

实质:函数重载
1 可以重载为普通函数也可以重载为成员函数
2 把含运算符的表达式转换成对运算符函数的调用
3 把运算符的操作数转换 成 运算符函数的参数
4 运算符被多次重载时,根据实参的类型决定调用哪个运算符函数

目的:扩展C++中提供的运算符的适用范围,使之能作用于对象。
 
同一运算符,对不同类型的操作数,所发生的行为不同

格式:
    返回类型 operator 运算符(参数表)
    {
    }
*/
#if 0
#include <iostream>
using namespace std;

class Complex
{
    public:
        double real , imag ;
        Complex( double r = 0.0 , double i = 0. ):real(r),imag(i)
        {
        }
        Complex operator-( const Complex & c );
};

Complex operator+( const Complex & a , const Complex & b )
{
    return Complex ( a.real + b.real , a.imag + b.imag );//返回临时对象
}

Complex Complex::operator-( const Complex & c )
{
    return Complex( real - c.real , imag - c.imag );//返回临时对象
}
//重载为成员函数时,参数个数为运算符数目减一
//重载为普通函数时,参数个数为运算符个数

int main()
{
    Complex a ( 4 , 4 ) , b ( 1 , 1 ), c ;
    c = a + b ;//c = operator +(a,b)
    cout << c.real << "," << c.imag << endl ;
    cout << (a-b).real << "," << (a-b).imag << endl ;//a-b=a.operator-(b)
    return 0;
}
#endif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值