C专家编程 第11章 你懂得C,所以C++不再话下 11.11 C++如何进行操作符重载

    C++如何进行操作数重载
    重载"+"操作符,为水果类定义加法操作。首先,增加水果类的加法操作符原型:
    class Fruit {
        public: void peel(); slice(); juice();
        int operator+(Fruit &f);  //重载+操作符
        private: int weight, calories_per_oz; 
    }; 
    然后为重载的操作符函数提供一个函数体:
    int Fruit::operator+(Fruit &f) {
        printf("calling fruit addition\n"); //这样我们就能看见它被调用
        return weight + f.weight; 
    } 
    和以前一样,每个成员函数都传递了一个隐式的this指针,允许我们引用操作符的左操作数。这里,加法的右操作数是参数f,它是Fruit类的一个实例,它前面的&表示它是通过传址调用的。这个重载的加法操作符函数可以像下面这样调用:
    Apple apple;
    Fruit orange;
    int ounces = apple + orange;
    重载后的操作符优先级和操作数(编译器行话中的arity)与原先的操作符相同。这样,你可以发现,C++表示如果你预先定义加法操作符,就可以把苹果和桔子相加。重载在C++中也非常方便。 

    /*
    ** operator overload.
    */
    #include <stdio.h>
    #include <stdlib.h>
    class Fruit {
        public:
            Fruit( int i, int j );
            void peel( void );
            void slice( void );
            void juice( void );
            int operator+(Fruit &f); //重载+操作符
        private: 
            int weight, calories_per_oz;
    };
    
    int main( void ){
        Fruit apple( 1, 2 ), banana( 3, 4 );
        int result = apple + banana;
    
        printf( "result = %d\n", result );
    
        return EXIT_SUCCESS;
    }
    
    Fruit::Fruit( int i, int j ){
        weight = i;
        this->calories_per_oz = j;
    }
    
    void Fruit::peel( void ){
        printf( "in peel!\n" );
    }
    
    void Fruit::slice( void ){
        printf( "in slice!\n" );
    }
    
    void Fruit::juice( void ){
        printf( "in juice!\n" );
    }
    
    int Fruit::operator+ ( Fruit &f ){
        printf("calling fruit addition\n"); //这样我们就能看见它被调用
        int result, result2;
        result = weight + f.weight;
        result2 = this->weight + f.weight;?
        printf( "%d %d\n", result, result2 );
        return result;
    }
输出:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_40186813

你的能量无可限量。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值