首页 > 其他 > 详细

操作符的重载

时间:2019-05-08 13:04:52      阅读:154      评论:0      收藏:0      [点我收藏+]

操作符的重载可以扩展操作符的功能,操作符的重载以特殊形式的函数的方式进行

 定义:

    通过operator操作符可以定义特殊的函数。(本质是通过函数重载操作符)

Type operator sign(const Type p1,const Type p2)  //sign是操作符(+,-,*,/)
{
   Type ret;

  
   return ret;     
}

 

 

例(扩展+符号的功能):

#include <stdio.h>

class Complex 
{
    int a;
    int b;
public:
    Complex(int a = 0, int b = 0)
    {
        this->a = a;
        this->b = b;
    }
    
    int getA()
    {
        return a;
    }
    
    int getB()
    {
        return b;
    }
    
    friend Complex operator + (const Complex& p1, const Complex& p2);  // 定义类的友元函数
};

Complex operator + (const Complex& p1, const Complex& p2)  // 操作符 + 重载的定义。已经用函数扩展了操作符的功能
{
    Complex ret;
    
    ret.a = p1.a + p2.a;
    ret.b = p1.b + p2.b;
    
    return ret;
}

int main()
{

    Complex c1(1, 2);
    Complex c2(3, 4);
    Complex c3 = c1 + c2;         // 两种写法都行,直接调用operator + 函数。
    //Complex c3 = operator + (c1, c2)    
    
    printf("c3.a = %d, c3.b = %d\n", c3.getA(), c3.getB());
    
    return 0;
}

 

操作符的重载

原文:https://www.cnblogs.com/zsy12138/p/10830981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!