zoukankan      html  css  js  c++  java
  • Swift

    让已有的运算符对自定义的类和结构进行运算或者重新定义已有运算符的运算规则,这种机制被称为运算符重载。


    1,通过重载加号运算符,使自定义的两个坐标结构体对象实现相加:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    struct CenterPointer{
        var x=0, y=0
    }
     
    func + (left:CenterPointer, right:CenterPointer) -> CenterPonter{
        return CenterPointer(x:left.x+right.y, y:left.y+right.y)
    }
     
    let pointer1 = CenterPointer(x:2, y:3)
    let pointer2 = CenterPointer(x:4, y:5)
    let pointer3 = pointer1 + pointer2
     

    2,重载判断运算符,实现判断自定义类型是否相等

    1
    2
    3
    4
    5
    6
    7
    func == (left:CenterPointer, right:CenterPointer) -> Bool {
        return (left.x == right.x) && (left.y == right.y)
    }
     
    func != (left:CenterPointer, right:CenterPointer) -> Bool {
        return !(left == right)
    }
     

    3,组合运算符,即将其他运算符和赋值运算符组合在一起,注意要把运算符左参数设置成inout类型

    1
    2
    3
    4
    5
    6
    7
    func += (inout left:CenterPointer, right:CenterPointer){
        left = left + right
    }
     
    var pointer1 = CenterPointer(x:2, y:3)
    var pointer2 = CenterPointer(x:4, y:5)
    pointer1 += pointer2
  • 相关阅读:
    div显示和隐藏
    C语言求素数的算法
    日志分析概述
    Base64编码 概念和用途
    leetcode
    hdu2665-Kth number
    为什么要新加入的人不闻不问?
    实现微博@@@
    JAVA运行程序代码段
    IfSpeed 带宽计算
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/4838081.html
Copyright © 2011-2022 走看看