import Foundation
class Complex {
var real = 0
var virtual = 0
init(real: Int,virtual: Int) {
self.real = real;
self.virtual = virtual
}
func show() -> Void {
if real != 0 {
if virtual > 0 {
print("\(real)+\(virtual)i")
}else if virtual < 0 {
print("\(real)\(virtual)i")
}else {
print(real)
}
}else {
if virtual != 0 {
print("\(virtual)i")
}else {
print("0")
}
}
}
func add(_ other:Complex) -> Complex { //加法实现
let sum = Complex(real : self.real + other.real,virtual : self.virtual + other.virtual)
return sum
}
//重载运算符
static func ==(left:Complex,right:Complex) -> Bool {
if left.real == right.real && left.virtual == right.virtual {
return true
}
return false
}
static func + (left:Complex,right:Complex) -> Complex {
let res = Complex(real:left.real + right.real,virtual:left.virtual + right.virtual)
return res
}
static func - (left:Complex,right:Complex) -> Complex {
let res = Complex(real:left.real - right.real,virtual:left.virtual - right.virtual)
return res
}
static func * (left:Complex,right:Complex) -> Complex {
let realNum = left.real * right.real - left.virtual * right.virtual
let virtualNum = left.real * right.virtual + left.virtual * right.real
let res = Complex(real:realNum,virtual:virtualNum)
return res
}
}
var com1 = Complex(real: 3, virtual: 4)
com1.show()
var com2 = Complex(real: -3, virtual: -4)
com2.show()
var com3 = com2.add(com1)
com3.show()
var com4 = com1 + com2
com4.show()
var com5 = com1 - com2
com5.show()
var com6 = com1 * com2
com6.show()
extension Int {
static prefix func ++(num:inout Int) -> Int {
num += 1
return num
}
static postfix func ++(num:inout Int) -> Int {
let temp = num
num += 1
return temp
}
static prefix func --(num:inout Int) -> Int {
num -= 1
return num
}
static postfix func --(num:inout Int) -> Int {
let temp = num
num -= 1
return temp
}
}
var num = 100
var res = ++num
print(num,res)
res = --num
print(num,res)
var a = 100
//var b = a++
//print(a,b)
var b = a--
print(a,b)
var s1 = "china"
var s2 = "beijing"
if s1 == s2 {
print("s1 == s2")
} else {
print("s1 != s2")
}
var arr1 = ["s","d"];
var arr2 = ["d","d"];
if arr1 == arr2 {
print("arr1 == arr2")
} else {
print("arr1 != arr2")
}
var test1 = Complex(real: 3, virtual: 4)
var test2 = Complex(real: 3, virtual: 4)
test1.show()
test2.show()
if test1 === test2 {
print("test1 === test2")
} else {
print("test1 !== test2")
}
if test1 == test2 {
print("test1 == test2")
} else {
print("test1 != test2")
}
Swift运算符重载
最新推荐文章于 2024-10-30 16:57:58 发布